C#進程操作

來源:互聯網
上載者:User

總結一下進程的建立和終止的操作過程。看代碼:

public int CallPhoneExe(string arg) //arg為進程的命令列參數<br /> { WaitHandle[] waits =new WaitHandle[2]; //定義兩個WaitHandle值,用以控制進程的執行過程<br /> waits[0] = HSTOP; //AutoResetEvent HSTOP = new AutoResetEvent(false);<br /> waits[1] = GlobalStop;//AutoResetEvent GlobalStop = new AutoResetEvent(false);<br /> int iReturn=0;<br /> Process p = new Process();//建立一個進程<br /> p.StartInfo.Arguments = arg; //進程的命令列參數<br /> p.StartInfo.FileName = filepath;//進程啟動路徑</p><p> p.StartInfo.CreateNoWindow = true;//不顯示新進程的視窗<br /> p.StartInfo.RedirectStandardOutput = true;//輸出重新導向<br /> p.StartInfo.RedirectStandardError = true; //Redirect the error ouput!<br /> p.StartInfo.UseShellExecute = false;<br /> p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;</p><p> p.EnableRaisingEvents = true;<br /> p.Exited += new EventHandler(p_Exited); //進程自然結束後啟動p—Exited事件<br /> p.OutputDataReceived += new DataReceivedEventHandler(ChangeOutput);//進程有輸出時,啟動ChangeOutPut函數 </p><p> p.Start();//進程啟動<br /> p.BeginOutputReadLine();</p><p> int hstop = WaitHandle.WaitAny(waits);//啟動線程暫停,知道WaitHandle中傳來有效訊號<br /> switch (hstop)//判斷訊號是又哪個<br /> {<br /> case 0: //進程自然結束<br /> if (p.WaitForExit(2000))<br /> iReturn = p.ExitCode; //擷取進程的傳回值<br /> else<br /> {<br /> CloseProcess();<br /> iReturn = -2;<br /> }<br /> break;<br /> case 1: //進程被迫結束<br /> p.Kill();//殺掉進程<br /> if (!p.HasExited)<br /> {<br /> p.Kill();<br /> }<br /> iReturn = -3;<br /> break;<br /> }<br /> HSTOP.Reset(); //HSTOP複位,這個變數指示進程自然結束,每次結束後都得自然複位<br /> p.Close(); //建立的p關閉<br /> return iReturn;<br /> }</p><p> private void p_Exited(object sender, EventArgs e)<br /> {<br /> HSTOP.Set();<br /> }</p><p>//輸出重新導向函數<br /> private void ChangeOutput(object sendingProcess, DataReceivedEventArgs outLine)<br /> {<br /> if (!String.IsNullOrEmpty(outLine.Data)) //字串不為空白時<br /> MainForm.FireWriteText(outLine.Data,false);//將進程的輸出資訊轉移<br /> }

上面總結了建立一個進程的步驟。結束進程的方法可以採用在主線程中將GlobalStop變數設定有效訊號,這樣就會調用p.kill()

 

 

 

在系統的所有進程中找尋指定進程的方法:

     foreach (Process p in Process.GetProcesses())
            {
                if (p.ProcessName == "specialProcess")
                {
                    //do smth

                }
                   
            }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.