C#啟動外部程式的幾種常用方法彙總
阿新 • • 發佈:2018-12-12
轉自https://www.cnblogs.com/randyzhuwei/p/5403922.html
本文彙總了C#啟動外部程式的幾種常用方法,非常具有實用價值,主要包括如下幾種方法:
- 啟動外部程式,不等待其退出。
- 啟動外部程式,等待其退出。
- 啟動外部程式,無限等待其退出。
- 啟動外部程式,通過事件監視其退出。
1. 啟動外部程式,不等待其退出
private string appName = "calc.exe"; private void button1_Click(object sender, EventArgs e) { Process.Start(appName); MessageBox.Show(String.Format("外部程式 {0} 啟動完成!", this.appName), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); }
2.啟動外部程式,等待其退出
private void button2_Click(object sender, EventArgs e) { try { Process proc = Process.Start(appName); if (proc != null) { proc.WaitForExit(3000); if (proc.HasExited) { MessageBox.Show(String.Format("外部程式 {0} 已經退出!", this.appName), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); } else { // 如果外部程式沒有結束執行則強行終止之。 proc.Kill(); MessageBox.Show(String.Format("外部程式 {0} 被強行終止!", this.appName), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } catch (ArgumentException ex) { MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
3.啟動外部程式,無限等待其退出
private void button3_Click(object sender, EventArgs e) { try { Process proc = Process.Start(appName); if (proc != null) { proc.WaitForExit(); MessageBox.Show(String.Format("外部程式 {0} 已經退出!", this.appName), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (ArgumentException ex) { MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
4.啟動外部程式,通過事件監視其退出
private void button4_Click(object sender, EventArgs e)
{
try
{
//啟動外部程式
Process proc = Process.Start(appName);
if (proc != null)
{
//監視程序退出
proc.EnableRaisingEvents = true;
//指定退出事件方法
proc.Exited += new EventHandler(proc_Exited);
}
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
///啟動外部程式退出事件
/// </summary>
void proc_Exited(object sender, EventArgs e)
{
MessageBox.Show(String.Format("外部程式 {0} 已經退出!", this.appName), this.Text,
MessageBoxButtons.OK, MessageBoxIcon.Information);
}