search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

C# 使用Process來達到呼叫、監聽、關閉外部程式等功能 – jashliao部落格

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 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦