天天看點

啟動一個程序并處理程序結束事件

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

  }

 }

}