天天看点

启动一个进程并处理进程结束事件

namespace rooksoft.Demo {

 public class OpenProcess {

  //静态变量表示当前程序运行中

  static bool IsRunning = true;

  public static void Main() {

   //建立一个进程对象

   System.Diagnostics.Process p = new System.Diagnostics.Process();

   //添加该进程结束事件处理函数

   p.Exited += new System.EventHandler(OpenProcess.Process_OnExit);

   p.EnableRaisingEvents = true;

   p.SynchronizingObject = null;

   p.StartInfo.FileName = "notepad.exe";

   //启动进程

   p.Start();

   //保持程序运行

   while (IsRunning) {

    System.Threading.Thread.Sleep(1000);

   }

  }

  //进程结束事件处理函数

  static void Process_OnExit(object sender, System.EventArgs e) {

   System.Windows.Forms.MessageBox.Show("Notepad was closed");

   IsRunning = false;

   //把标示设置成false

  }

 }

}