this.openFileDialog.ShowDialog();
this.txtFileName.Text = this.openFileDialog.FileName;
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = txtFileName.Text;//外部程式名稱
//設定外部程式工作目錄
info.WorkingDirectory = txtFileName.Text.ToString().Substring(0, this.txtFileName.Text.LastIndexOf("\\"));
this.WorkingDirectory.Text = info.WorkingDirectory;
Process process;
try
{
process = Process.Start(info);//啟動外部程式
}
catch (Win32Exception exception)
{
MessageBox.Show("系統找不到指定的程式檔案:" + exception.Message);
return;
throw;
}
this.startTime.Text = process.StartTime.ToString();//外部程式運行開始時間
process.WaitForExit(3000);//設定等待3秒後由主程式進行關閉外部程式
if (process.HasExited == false)
{
this.exitType.Text = "由主程式強制終止外部程式運行";
process.Kill();//強制關閉外部程式
this.endTime.Text = DateTime.Now.ToString();
}
else
{
this.exitType.Text = "外部程式正常退出";
this.endTime.Text = process.ExitTime.ToString();//外部程式執行結束退出時間
}
監測外部程式是否退出:
process.EnableRaisingEvents = true;
process.Exited += new EventHandler(process_Exited);
public void process_Exited(object sender, EventArgs e)
{
MessageBox.Show("已監測到外部程式退出。");
}
另外:
監測外部程式是否退出的兩個方法:以運行系統記事本為例
方法一:這種方法會阻塞當前進程,直到啟動並執行外部程式退出
System.Diagnostics.Process exep = System.Diagnostics.Process.Start(@"C:\Windows\Notepad.exe");
exep.WaitForExit();//關鍵,等待外部程式退出後才能往下執行
MessageBox.Show("Notepad.exe運行完畢");
方法二:為外部進程添加一個事件監視器,當退出後,擷取通知,這種方法時不會阻塞當前進程,你可以處理其它事情
System.Diagnostics.Process exep = new System.Diagnostics.Process();
exep.StartInfo.FileName = @"C:\Windows\Notepad.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運行完畢");
}
Demo下載