標籤:winform style class blog code http
目標:想在WinForm程式之間傳遞參數。以便子進程作出相應的處理。
一種錯誤的方法
父進程的主程式:
1 ProcessStartInfo psi = new ProcessStartInfo();2 psi.FileName = "ProcessChild.exe";3 psi.Arguments = txtArgs.Text;4 Process.Start(psi);//主要問題在這裡
子進程的主程式:
1 txtArgs.Text = Process.GetCurrentProcess().StartInfo.Arguments;
結果
根本就傳不過來的,錯誤的原因在於:想當然的認為父進程的ProcessStartInfo這個類的執行個體的成員Arguments傳遞到子進程中去了。其實Process.Start()返回一個Process類型的對象,資料在返回的對象中儲存著,並沒有跨進程傳遞。
兩種正確的方法
第一種:
從Main(string []args)接收傳入的資料。這裡要修改子進程的Main方法如下:
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.
當從父進程啟動時,父進行傳遞的參數成為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 }
找到原因的地址: http://stackoverflow.com/questions/10682212/how-to-pass-argument-to-a-process