淺談C#中Process類的使用詳解

來源:互聯網
上載者:User

Process類的作用是對系統進程進行管理,我們使用Process類中的一些方法結合Winform開發個簡單的進程管理器:

在使用Process類的時候,先匯入命名空間System.Diagnostics。
使用Winform畫出如上的介面,資料顯示使用的是Listview。
在表單的Load事件中寫出如下代碼:

複製代碼 代碼如下: private void Form1_Load(object sender, EventArgs e)
{

listView1.FullRowSelect = true;

GetProcess();
}

其中GetProcess方法如下:
複製代碼 代碼如下: private void GetProcess()
{
listView1.Items.Clear();

Process[] proList = Process.GetProcesses(".");//獲得原生進程

lblNum.Text = proList.Length.ToString(); //當前進程數量
foreach (Process p in proList)
{
ListViewItem lvi = new ListViewItem();

lvi.Text = p.ProcessName;

lvi.SubItems.AddRange(new string[] { p.Id.ToString(),p.PrivateMemorySize64.ToString() }); //進程ID 使用記憶體

listView1.Items.Add(lvi);
}
}

如果想終止一個進程,先選中一個進程,點擊上面的進程按鈕:
click事件代碼如下:複製代碼 代碼如下: private void button2_Click(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
try
{
string proName = listView1.SelectedItems[0].Text;
Process[] p = Process.GetProcessesByName(proName); //根據進程命獲得指定的進程
p[0].Kill(); //殺死該進程
MessageBox.Show("進程關閉成功!");
GetProcess();
}
catch
{
MessageBox.Show("無法關閉此進程!");
}

}
else
{
MessageBox.Show("請選擇要終止的進程!");
}
}

當然我們可以調用Process的start方法來開啟一個進程:
啟動按鈕的事件如下:複製代碼 代碼如下: private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != string.Empty)
{
Process.Start(textBox1.Text); //啟動一個進程
}
else
{
MessageBox.Show("請輸入啟動項");
textBox1.Focus();
}

}

運行程式,開始使用自己的進程管理器吧~~~~~

相關文章

聯繫我們

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