得到系統進程和結束某個指定的進程 (C#)

來源:互聯網
上載者:User
得到系統當前進程,加入到listBox中:
System.Diagnostics.Process[] processOnComputer = System.Diagnostics.Process.GetProcesses();
foreach ( System.Diagnostics.Process p in processOnComputer )
{
this.listBox1.Items.Add(p.ProcessName);

}

 

關閉某個指定的進程:
System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName(this.listBox1.SelectedItem.ToString());
foreach ( System.Diagnostics.Process p in process)
{
p.Kill();
}

但是這樣會關閉進程的所有執行個體,比如如果你開啟了多個IE,會把所有的IE視窗都關閉 

 

下面實現關閉某個特定的IE執行個體
先聲明一個ArrayList:
ArrayList windowHandle = new ArrayList();

得到指定進程的所有執行個體,放到一個ListBox中,同時把主視窗的Handle放到ArrayList中:
System.Diagnostics.Process[] processOnComputer = System.Diagnostics.Process.GetProcessesByName(this.listBox1.SelectedItem.ToString());
foreach ( System.Diagnostics.Process p in processOnComputer )
{
this.listBox2.Items.Add(p.MainWindowTitle);//在ListBox中顯示主表單的標題
windowHandle.Add(p.MainWindowHandle);
}

把指定的進程的主視窗的Handle和ArrayList中的比對,如果符合就關閉 
System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName(this.listBox1.SelectedItem.ToString());
foreach ( System.Diagnostics.Process p in process )
{
if ( p.MainWindowHandle == (System.IntPtr)(windowHandle[this.listBox2.SelectedIndex]))
{
p.Kill();
this.listBox2.Items.RemoveAt(this.listBox2.SelectedIndex);
}
}

這樣可以關閉有主表單的進程,但是沒有主表單的還不行 

聯繫我們

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