学习《C#网络应用编程》的一个开始,在博客上记录下源码以便日后翻用。
引入命名空间:
using System.Diagnostics;
然后直接贴源码啦
namespace ProcessMonitor
{
public partial class Form1 : Form
{
Process[] myProcess;
public Form1()
{
InitializeComponent();
dgv_Process.AutoResizeColumns();
}
private void btn_Refurbish_Click(object sender, EventArgs e)
{
GetAllProcessToControl();
}
private void Form1_Load(object sender, EventArgs e)
{
GetAllProcessToControl();
}
/// <summary>
/// 获取全部进程并填充到dgv_Process控件中
/// </summary>
private void GetAllProcessToControl()
{
dgv_Process.Rows.Clear();
myProcess = Process.GetProcesses();
foreach (Process p in myProcess)
{
int newRowIndex = dgv_Process.Rows.Add();
DataGridViewRow row = dgv_Process.Rows[newRowIndex];
row.Cells[0].Value = p.Id;
row.Cells[1].Value = p.ProcessName;
row.Cells[2].Value = string.Format("{0:###,##0.00}MB", p.WorkingSet64 / 1024.0f / 1024.0f);
//有些进程无法获取启动时间和文件信息,所以要用try/catch
try
{
row.Cells[3].Value = string.Format("{0}", p.StartTime);
row.Cells[4].Value = p.MainModule.FileName;
}
catch (Exception)
{
row.Cells[3].Value = "";
row.Cells[4].Value = "";
//throw;
}
}
}
private void ShowProcessInfo(Process p)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("进程名称:" + p.ProcessName + ", ID:" + p.Id);
try
{
sb.AppendLine("进程优先级" + p.BasePriority + "(优先级别:" + p.PriorityClass + ")");
ProcessModule m = p.MainModule;
sb.AppendLine("文件名:" + m.FileName);
sb.AppendLine("版本:" + m.FileVersionInfo.FileVersion);
sb.AppendLine("描述:" + m.FileVersionInfo.FileDescription);
sb.AppendLine("语言:" + m.FileVersionInfo.Language);
sb.AppendLine("--------------------------------");
if (p.Modules != null)
{
ProcessModuleCollection pmc = p.Modules;
sb.AppendLine("调用的模块(.dll):");
for (int i = 1; i < pmc.Count; i++)
{
sb.AppendLine(
"模块名:" + pmc[i].ModuleName + "\t" +
"版本:" + pmc[i].FileVersionInfo.FileVersion + "\t" +
"描述:" + pmc[i].FileVersionInfo.FileDescription);
}
}
}
catch (Exception)
{
sb.AppendLine("其他信息:无法获取");
//throw;
}
this.txt_ProcessInfo.Text = sb.ToString();
}
private void dgv_Process_MouseClick(object sender, MouseEventArgs e)
{
DataGridView.HitTestInfo h = dgv_Process.HitTest(e.X, e.Y);
if (h.Type == DataGridViewHitTestType.Cell || h.Type == DataGridViewHitTestType.RowHeader)
{
dgv_Process.Rows[h.RowIndex].Selected = true;
int processId = (int)dgv_Process.CurrentRow.Cells[0].Value;
ShowProcessInfo(Process.GetProcessById(processId));
}
}
}
}
界面截图: