1. 程式人生 > 其它 >C#呼叫Exe檔案的方法及如何判斷程式呼叫的exe已結束(轉)

C#呼叫Exe檔案的方法及如何判斷程式呼叫的exe已結束(轉)

引入using System.Diagnostics;

呼叫程式碼:

Process.Start(exe檔名);

或直接

System.Diagnostics.Process.Start(exe檔名);

C#如何判斷程式呼叫的exe已結束

二個方法:以執行系統記事本為例

方法一:這種方法會阻塞當前程序,直到執行的外部程式退出
System.Diagnostics.Process exep = System.Diagnostics.Process.Start(@"C:WindowsNotepad.exe");
exep.WaitForExit();//關鍵,等待外部程式退出後才能往下執行
MessageBox.Show("Notepad.exe執行完畢");

方法二:為外部程序新增一個事件監視器,當退出後,獲取通知,這種方法時不會阻塞當前程序,你可以處理其它事情
System.Diagnostics.Process exep = new System.Diagnostics.Process();
exep.StartInfo.FileName = @"C:WindowsNotepad.exe";
exep.EnableRaisingEvents = true;
exep.Exited += new EventHandler(exep_Exited);
exep.Start();

//exep_Exited事件處理程式碼,這裡外部程式退出後啟用,可以執行你要的操作
void exep_Exited(object sender, EventArgs e)
{
MessageBox.Show("Notepad.exe執行完畢");
}