一年多沒接觸C#開發了,複習一下Winform方面的知識:
C#開啟、關閉進程,擷取進程列表;
有圖有真相:
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Text;
7 using System.Windows.Forms;
8 using System.Diagnostics;
9 using System.Threading;
10
11 namespace ProcessExample
12 {
13
14 public partial class Form1 : Form
15 {
16
17 public Form1()
18 {
19 InitializeComponent();
20 }
21
22 private void buttonStart_Click(object sender, EventArgs e)
23 {
24 process1.StartInfo.FileName = "notepad.exe";
25 //啟動Notepad.exe進程.
26 process1.Start();
27 }
28 private void buttonStop_Click(object sender, EventArgs e)
29 {
30 //建立新的Process組件的數組,並將它們與指定的進程名稱(Notepad)的所有進程資源相關聯.
31 Process[] myprocesses;
32 myprocesses = Process.GetProcessesByName("Notepad");
33 foreach (Process instance in myprocesses)
34 {
35 //設定終止當前線程前等待1000毫秒
36 instance.WaitForExit(1000);
37 instance.CloseMainWindow();
38 }
39 }
40 private void buttonView_Click(object sender, EventArgs e)
41 {
42 listBox1.Items.Clear();
43 //建立Process類型的數組,並將它們與系統內所有進程相關聯
44 Process[] processes;
45 processes = Process.GetProcesses();
46 foreach (Process p in processes)
47 {
48 //Idle指顯示CPU空閑率的進程名稱
49 //由於訪問Idle的StartTime會出現異常,所以將其排除在外
50 if (p.ProcessName != "Idle")
51 {
52 //將每個進程名和進程開始時間加入listBox1中
53 this.listBox1.Items.Add(
54 string.Format("{0,-30}{1:h:m:s}", p.ProcessName, p.StartTime));
55 }
56 }
57 }
58 }
59 }