编写代码前添加:using System.Diagnostics;
1.获取本机的
string processName;//进程名成
int processID;//ID
int threadNumber;//进程数
TimeSpan cpuTime;//CPU时间
long processMemory;//内存数量
2.要实现的框架结构(添加三个菜单和一个listView),listView的属性设置见上篇C#中控件的应用:
为三个菜单添加事件处理函数,分别添加代码:
private void 创建进程ToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog ofDlg = new OpenFileDialog();//构建打开文件对话框
ofDlg.Filter = "All Executables(*.exe)|*.exe";//筛选
if (ofDlg.ShowDialog() == DialogResult.OK)
{
try
{
Process newprocess = Process.Start(ofDlg.FileName);//选择进程
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
private void 刷新列表ToolStripMenuItem_Click(object sender, EventArgs e)
{//显示进程信息
string processName;//进程名成
int processID;//ID
int threadNumber;//进程数
TimeSpan cpuTime;//CPU时间
long processMemory;//内存数量
listView1.Items.Clear();//清除列表视图中原有的内容
Process[] processes = Process.GetProcesses();//定义动态数组,获得当前系统中的所有进程
try
{
//在列表中加入每个进程项目
for (int i = 0; i < processes.Length; i++)
{
processName = processes[i].ProcessName;
processID = processes[i].Id;
threadNumber = processes[i].Threads.Count;//获得进程的数量
cpuTime = processes[i].TotalProcessorTime;
processMemory = processes[i].WorkingSet64;
string[] subItems =
{
processName,
processID.ToString(),
threadNumber.ToString(),
string.Format("{0:00}:{1:00}:{2:00}",
cpuTime.Hours,cpuTime.Minutes,cpuTime.Seconds),
string.Format("{0:#,#,#}k",processMemory/1024)
};
//插入一行项目
listView1.Items.Insert(i, new ListViewItem(subItems));
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void 结束进程ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
string str = listView1.SelectedItems[0].SubItems[1].Text;
int processID = Int32.Parse(str);//获取选中项目的ID 值
//根据ID获取进程
Process selectedProcess = Process.GetProcessById(processID);
selectedProcess.Kill();//终止进程
}
}
4.结果如图: