public int CallPhoneExe(string arg) //arg爲進程的命令行參數 {
WaitHandle[] waits =new WaitHandle[2]; //定義兩個WaitHandle值,用以控制進程的執行過程 waits[0] = HSTOP; //AutoResetEvent HSTOP = new AutoResetEvent(false); waits[1] = GlobalStop;//AutoResetEvent GlobalStop = new AutoResetEvent(false); int iReturn=0; Process p = new Process();//新建一個進程 p.StartInfo.Arguments = arg; //進程的命令行參數 p.StartInfo.FileName = filepath;//進程啓動路徑 p.StartInfo.CreateNoWindow = true;//不顯示新進程的窗口 p.StartInfo.RedirectStandardOutput = true;//輸出重定向 p.StartInfo.RedirectStandardError = true; //Redirect the error ouput! p.StartInfo.UseShellExecute = false; p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; p.EnableRaisingEvents = true; p.Exited += new EventHandler(p_Exited); //進程天然結束後啓動p—Exited事件 p.OutputDataReceived += new DataReceivedEventHandler(ChangeOutput);//進程有輸出時,啓動ChangeOutPut函數 p.Start();//進程啓動 p.BeginOutputReadLine(); int hstop = WaitHandle.WaitAny(waits);//啓動線程暫停,知道WaitHandle中傳來有效信號 switch (hstop)//判斷信號是又哪一個 { case 0: //進程天然結束 if (p.WaitForExit(2000)) iReturn = p.ExitCode; //獲取進程的返回值 else { CloseProcess(); iReturn = -2; } break; case 1: //進程被迫結束 p.Kill();//殺掉進程 if (!p.HasExited) { p.Kill(); } iReturn = -3; break; } HSTOP.Reset(); //HSTOP復位,這個變量指示進程天然結束,每次結束後都得天然復位 p.Close(); //建立的p關閉 return iReturn; } private void p_Exited(object sender, EventArgs e) { HSTOP.Set(); } //輸出重定向函數 private void ChangeOutput(object sendingProcess, DataReceivedEventArgs outLine) { if (!String.IsNullOrEmpty(outLine.Data)) //字符串不爲空時 MainForm.FireWriteText(outLine.Data,false);//將進程的輸出信息轉移 }
上述代碼基本囊括了對進程Process的操做。在C#工具箱中包括進程這一個組件。函數