本文說明如何使用 Microsoft .NET Framework Process
類別,從程式代碼啟動另一個應用程式,並讓程式代碼等候其他應用程式關閉,再繼續進行。
原始產品版本: Visual C# .NET
原始 KB 編號: 305369
摘要
當程式代碼等候應用程式完成時,有兩個選項:
- 無限期等候其他應用程式完成或由用戶關閉。
- 指定逾時期間,之後您可以從程式碼關閉應用程式。
本文提供兩個示範這兩種方法的程式碼範例。 此外,逾時範例允許其他應用程式可能已停止回應(無回應),並採取必要步驟關閉應用程式。
本文參考下列 .NET Framework 類別庫命名空間 System.Diagnostics
。
包含命名空間
您應該先匯入 類別的 Process
命名空間,再執行下列範例。 將下列程式代碼行放在包含程式代碼範例的 Namespace 或 Class 宣告之前:
using System.Diagnostics;
無限期等候殼層應用程式完成
下列程式代碼範例會啟動另一個應用程式(在此案例中為記事本),並無限期等候應用程式關閉:
//How to Wait for a Shelled Process to Finish
//Get the path to the system folder.
string sysFolder=
Environment.GetFolderPath(Environment.SpecialFolder.System);
//Create a new process info structure.
ProcessStartInfo pInfo = new ProcessStartInfo();
//Set the file name member of the process info structure.
pInfo.FileName = sysFolder + @"\eula.txt";
//Start the process.
Process p = Process.Start(pInfo);
//Wait for the window to finish loading.
p.WaitForInputIdle();
//Wait for the process to end.
p.WaitForExit();
MessageBox.Show("Code continuing...");
為殼層應用程式提供逾時
下列程式代碼範例會設定殼層應用程式的逾時。 此範例的逾時設定為5秒。 您可能想要調整此數位(以毫秒為單位計算),以供測試使用。
//Set a time-out value.
int timeOut=5000;
//Get path to system folder.
string sysFolder=
Environment.GetFolderPath(Environment.SpecialFolder.System);
//Create a new process info structure.
ProcessStartInfo pInfo = new ProcessStartInfo();
//Set file name to open.
pInfo.FileName = sysFolder + @"\eula.txt";
//Start the process.
Process p = Process.Start(pInfo);
//Wait for window to finish loading.
p.WaitForInputIdle();
//Wait for the process to exit or time out.
p.WaitForExit(timeOut);
//Check to see if the process is still running.
if (p.HasExited == false)
//Process is still running.
//Test to see if the process is hung up.
if (p.Responding)
//Process was responding; close the main window.
p.CloseMainWindow();
else
//Process was not responding; force the process to close.
p.Kill();
MessageBox.Show("Code continuing...");
疑難排解
有時候可能很難在這兩個選項之間進行選擇。 逾時的主要目的是防止應用程式停止回應,因為其他應用程式已停止回應。 逾時更適合執行背景處理的殼層應用程式,其中使用者可能不知道其他應用程式已停滯或沒有方便的方式來關閉它。