3C科技 娛樂遊戲 美食旅遊 時尚美妝 親子育兒 生活休閒 金融理財 健康運動 寰宇綜合

Zi 字媒體

2017-07-25T20:27:27+00:00
加入好友
C# 使用Process來達到呼叫、監聽、關閉外部程式等功能 資料來源: http://fecbob.pixnet.net/blog/post/38088805-c#-啟動外部程式 GITHUB: https://github.com/jash-git/WinForm_Process_test PS [C# 啟動/呼叫/執行 外部程式/BAT/CONSOLE] 1. 啟動外部程式,不等待其退出。 // using System.Diagnostics; private string appName = "calc.exe"; /// /// 1. 啟動外部程式,不等待其退出 /// 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. 啟動外部程式,等待其退出。 // using System.Diagnostics; private string appName = "calc.exe"; /// /// 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. 啟動外部程式,無限等待其退出。 // using System.Diagnostics; private string appName = "calc.exe"; /// /// 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. 啟動外部程式,通過事件監視其退出。 // using System.Diagnostics; private string appName = "calc.exe"; /// /// 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); } } /// /// 啟動外部程式退出事件 /// void proc_Exited(object sender, EventArgs e) { MessageBox.Show(String.Format("外部程式 {0} 已經退出!", this.appName), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); }

本文由jashliaoeuwordpress提供 原文連結

寫了 5860316篇文章,獲得 23313次喜歡
精彩推薦