記一次WinForm程式中主進程開啟子進程並傳遞參數的操作過程(進程間傳遞參數)

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.