この記事では、Microsoft .NET Framework Process
クラスを使用してコードから別のアプリケーションを起動し、コードが他のアプリケーションが閉じるのを待ってから続行する方法について説明します。
元の製品バージョン: Visual C# .NET
元の KB 番号: 305369
まとめ
コードがアプリケーションの完了を待機する場合、次の 2 つのオプションがあります。
- 他のアプリケーションが終了するか、ユーザーによって閉じられるまで無期限に待機します。
- タイムアウト期間を指定すると、コードからアプリケーションを閉じることができます。
この記事では、両方の方法を示す 2 つのコード サンプルを示します。 さらに、タイムアウトの例では、他のアプリケーションが応答を停止 (ハング) している可能性があり、アプリケーションを閉じるのに必要な手順を実行できます。
この記事では、次の .NET Framework クラス ライブラリ名前空間 System.Diagnostics
について説明します。
名前空間を含める
次の例を実行する前に、 Process
クラスの名前空間をインポートする必要があります。 コード サンプルを含む名前空間またはクラス宣言の前に、次のコード行を配置します。
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...");
トラブルシューティング
場合によっては、これら 2 つのオプションの中から選択するのが難しい場合があります。 タイムアウトの主な目的は、他のアプリケーションがハングしているためにアプリケーションがハングするのを防ぐことです。 タイムアウトは、バックグラウンド処理を実行するシェルアプリケーションに適しています。このアプリケーションでは、他のアプリケーションがストールしているか、またはアプリケーションを閉じるのに便利な方法がない可能性があります。