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();
}
}
運行程式,開始使用自己的進程管理器吧~~~~~