今天公司讓我把Winform程序里的一塊單獨成一個exe文件,從原程序中打開新的exe程序,這就涉及到參數的傳遞,故來記錄下傳遞參數到exe程序的方式
第一種方式
首先在程序A中添加引用using System.Diagnostics;
string strA = "hello" + "," + "world";
Process pro = Process.Start(@"C:\testB.exe", strA);//打開程序B
pro.WaitForExit();
int Result = pro.ExitCode;//程序B退出回傳值
if (Result == 1)//接收到程序B退出代碼"1"
{
textBox1.Text = "退出程序B";
}
在程序B中的Program.cs
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
try
{
FormB.str = args[0].Trim();//用一個字符串來接收FormA中傳過來的數據
Application.Run(new Form1());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
這樣的話在B程序Form1中就接收到了程序A中傳過來的字符串strA
//將傳過來的數據放到textbox中
textBox1.Text =str;
效果.png
若點擊退出按鈕,退出系統時發生指定代碼,且這種退出方式是完全退出。
Environment.Exit(1);程序B退出回傳"1"
效果.png
第二種方式
System.Diagnostics.Process pro = new System.Diagnostics.Process();
pro.StartInfo.FileName = @"C:\testB.exe";
//傳入4個字符串
pro.StartInfo.Arguments = string.Format("{0} {1} {2} {3}", "hello", "world", "你好", "世界");
pro.Start();//開啟程序
程序B中的
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1(args));//也可以像第一種那樣實現
}
FormB頁面中
public static string[] temp;
public Form1(string[] args)
{
InitializeComponent();
temp = args;//因為傳過來的是一個數組,所以我們定義了一個新的全局空數組來接替他
}
//將傳過來的數據放到textbox中
textBox1.Text =temp[0]+temp[1]+temp[2]+temp[3];
FormB頁面.png