C#进程监控方法实例分析
本文实例讲述了C#进程监控方法。分享给大家供大家参考。具体如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Text; usingSystem.Windows.Forms; usingSystem.Diagnostics; namespaceProcessMonitor { publicpartialclassForm1:Form { Process[]myProcess; publicForm1() { InitializeComponent(); dataGridView1.AllowUserToAddRows=false; dataGridView1.AutoResizeColumns(); dataGridView1.AutoSizeColumnsMode=DataGridViewAutoSizeColumnsMode.AllCells; dataGridView1.MultiSelect=false; } privatevoidForm1_Load(objectsender,EventArgse) { GetAllProcess(); } privatevoidGetAllProcess() { dataGridView1.Rows.Clear(); myProcess=Process.GetProcesses(); foreach(ProcesspinmyProcess) { intnewRowIndex=dataGridView1.Rows.Add(); DataGridViewRowrow=dataGridView1.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 { row.Cells[3].Value=""; row.Cells[4].Value=""; } } } privatevoidShowProcessInfo(Processp) { StringBuildersb=newStringBuilder(); sb.AppendLine("进程名称:"+p.ProcessName+",ID:"+p.Id); try { sb.AppendLine("进程优先级:"+p.BasePriority+"(优先级类别:"+p.PriorityClass+")"); ProcessModulem=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) { ProcessModuleCollectionpmc=p.Modules; sb.AppendLine("调用的模块(.dll):"); for(inti=1;i<pmc.Count;i++) { sb.AppendLine( "模块名:"+pmc[i].ModuleName+"\t"+ "版本:"+pmc[i].FileVersionInfo.FileVersion+"\t"+ "描述:"+pmc[i].FileVersionInfo.FileDescription); } } } catch { sb.AppendLine("其他信息:无法获取"); } this.richTextBox1.Text=sb.ToString(); } privatevoidbuttonRefresh_Click(objectsender,EventArgse) { GetAllProcess(); } privatevoiddataGridView1_MouseClick(objectsender,MouseEventArgse) { //DataGridView.HitTestInfoh=dataGridView1.HitTest(e.X,e.Y); //if(h.Type==DataGridViewHitTestType.Cell||h.Type==DataGridViewHitTestType.RowHeader) //{ //dataGridView1.Rows[h.RowIndex].Selected=true; //intprocesseId=(int)dataGridView1.CurrentRow.Cells[0].Value; //ShowProcessInfo(Process.GetProcessById(processeId)); //} } privatevoiddataGridView1_CellClick(objectsender,DataGridViewCellEventArgse) { try { if(e.RowIndex>=0) { intprocessId=(int)dataGridView1.Rows[e.RowIndex].Cells[0].Value; ShowProcessInfo(Process.GetProcessById(processId)); } } catch(Exceptionex) { MessageBox.Show("发生异常,原因是:"+ex.Message); } } } }
希望本文所述对大家的C#程序设计有所帮助。