Visual C# を使用してシェル化されたアプリケーションの完了を待機する

この記事では、Microsoft .NET Framework Process クラスを使用してコードから別のアプリケーションを開始し、コードが他のアプリケーションが閉じるのを待ってから続行する方法について説明します。

元の製品バージョン: Visual C# .NET
元の KB 番号: 305369

概要

コードがアプリケーションの完了を待機すると、次の 2 つのオプションがあります。

  • 他のアプリケーションが終了するか、ユーザーによって閉じられるまで無期限に待機します。
  • タイムアウト期間を指定し、その後、コードからアプリケーションを閉じることができます。

この記事では、両方の方法を示す 2 つのコード サンプルを示します。 さらに、タイムアウトの例では、他のアプリケーションが応答を停止 (ハング) している可能性があり、アプリケーションを閉じるのに必要な手順を実行できます。

この記事では、次の .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...");

トラブルシューティング

場合によっては、これら 2 つのオプションの中から選択するのが難しい場合があります。 タイムアウトの主な目的は、他のアプリケーションがハングしたためにアプリケーションがハングするのを防ぐことです。 タイムアウトは、バックグラウンド処理を実行するシェル化されたアプリケーションに適しています。ユーザーは、他のアプリケーションがストールしているか、便利な方法で閉じていない可能性があります。