記一次WinForm程序中主進程打開子進程並傳遞參數的操做過程(進程間傳遞參數)

目標:想在WinForm程序之間傳遞參數。以便子進程做出相應的處理。spa

 

 一種錯誤的方法3d

 父進程的主程序:code

1             ProcessStartInfo psi = new ProcessStartInfo();
2             psi.FileName = "ProcessChild.exe";
3             psi.Arguments = txtArgs.Text;
4             Process.Start(psi);//主要問題在這裏

 子進程的主程序:orm

 1 txtArgs.Text = Process.GetCurrentProcess().StartInfo.Arguments; 對象

結果如圖:blog

根本就傳不過來的,錯誤的緣由在於:想固然的認爲父進程的ProcessStartInfo這個類的實例的成員Arguments傳遞到子進程中去了。其實Process.Start()返回一個Process類型的對象,數據在返回的對象中保存着,並無跨進程傳遞。進程

 兩種正確的方法字符串

 第一種:get

  從Main(string []args)接收傳入的數據。這裏要修改子進程的Main方法以下:string

1         static void Main(string []args)
2         {
3             Application.EnableVisualStyles();
4             Application.SetCompatibleTextRenderingDefault(false);
5             Application.Run(new frmChild());
6         }

 

 由於默認是沒有參數的。保存args裏面的字符串,值得一提的是:args老是有至少一個元素,第二種方法方便看到。

第二種:使用Environment類的方法。

1             string[] args = Environment.GetCommandLineArgs();
2            //txtArgs.Text = Process.GetCurrentProcess().StartInfo.Arguments;
3             txtArgs.Text = args[0] + "\r\n";

 

當不從父進程啓動時,結果以下:args的元素個數是1或者更多,第0個是固定的.

當從父進程啓動時,父進行傳遞的參數成爲args的第二個元素:子進程中代碼

1             string[] args = Environment.GetCommandLineArgs();
2            //txtArgs.Text = Process.GetCurrentProcess().StartInfo.Arguments;
3             txtArgs.Text += args[0] + "\r\n";
4             if (args.Length > 1)
5             {
6                 txtArgs.Text += args[1];
7             }

 

  還有一個地方須要注意:那就是當父程序傳遞參數時,若是傳遞來的字符串內有空格的話,那會被當成參數的分界,像下面這樣:

 1           
 2 ///////////////////////////////////父程序///////////////////////
 3             ProcessStartInfo psi = new ProcessStartInfo();
 4             psi.FileName = @"C:\Documents and Settings\Administrator\桌面\ProcessArgs\ProcessChild\bin\Debug\ProcessChild.exe";
 5             psi.Arguments = txtArgs.Text;
 6             Process.Start(psi);//主要問題在這裏
 7 //
 8 ///////////////////////////////////子程序///////////////////////
 9  string[] args = Environment.GetCommandLineArgs();
10            txtArgs.Text += "第0個參數" + args[0]+"\r\n";
11            int i = 1;
12            MessageBox.Show(args.Length.ToString());
13            if (args.Length > 1)//看子程序是怎麼接收數據的
14            {
15                while (i < args.Length)
16                {
17                    txtArgs.Text += ""+i+"個參數:"+args[i]+"\r\n ";
18                    i++;
19                }
20            }
21            txtArgs.Text += "傳遞過來的參數個數是:"+args.Length.ToString();
22 //結果:
23 第0個參數C:\Documents and Settings\Administrator\桌面\ProcessArgs\ProcessChild\bin\Debug\ProcessChild.exe
24 第1個參數:這是從父進行傳遞來的參數
25  第2個參數:空格1
26  第3個參數:空格2
27  傳遞過來的參數個數是:4

 

在父程序傳遞數據如圖:

子程序接收到狀況以下:

子程序

找到緣由的地址:  http://stackoverflow.com/questions/10682212/how-to-pass-argument-to-a-process

相關文章
相關標籤/搜索