いくつかのプログラムを 1 つずつ実行したいのですが、メッセージやエラーを確認するためにコンソール ウィンドウを開いたままにしたい場合があります。
cmd.exe /K anotherProgram.exe
を実行し、anotherProgram が終了するまで待ち ( WaitForExit()
)、anotherProgram の exitCode を取得する可能性はありますか? または、から実行する以外の方法でコンソールを開いたままにすることができcmd /K
ますか?
コンソール プログラムの出力とエラー ストリームをキャプチャして、メッセージ/エラーを取得できます。そうすれば、プログラムの終了コードも取得できます。
Processクラスで利用可能なイベントを見てみましょう。
Process.OutputDataReceived イベント==> これを使用して、標準出力メッセージをキャプチャします
Process.ErrorDataReceived イベント==> これを使用してエラー メッセージをキャプチャします
Process.Exited Event ==> これを使用して終了コードを取得します
以下は、コンソール ウィンドウが表示されず、出力とエラー ストリームがキャプチャされてメッセージ ボックスに表示される (例外処理と引数テストなしの) ドライブのフォーマットに関する例です。終了コードは、プロセスの終了時にもチェックされます。
private Process formatProc;
Private void DoFormat(string driveLetter)
this.formatProc = new Process
{
StartInfo =
{
UseShellExecute = false,
FileName = "format.com",
Arguments = string.Format("/FS:FAT {0}: /V: /Q", driveLetter),
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden
},
EnableRaisingEvents = true
};
this.formatProc.OutputDataReceived += this.ProcOutputDataReceivedHandler;
this.formatProc.ErrorDataReceived += this.ProcErrorDataReceivedHandler;
this.formatProc.Exited += this.ProcExitedHandler;
this.formatProc.Start();
this.formatProc.BeginOutputReadLine();
this.formatProc.BeginErrorReadLine();
}
private void ProcOutputDataReceivedHandler(object sendingProcess, DataReceivedEventArgs e)
{
if (string.IsNullOrEmpty(e.Data))
{
MessageBox.Show(e.Data);
}
}
private void ProcErrorDataReceivedHandler(object sendingProcess, DataReceivedEventArgs e)
{
if (string.IsNullOrEmpty(e.Data))
{
MessageBox.Show(e.Data);
}
}
private void ProcExitedHandler(object sender, EventArgs e)
{
var exitCode = this.formatProc.ExitCode;
var message = string.Empty;
switch (exitCode)
{
case 0:
message = "Format done.";
break;
case 1:
message = "Format failed. Incorrect parameters were supplied.";
break;
case 4:
message = "Format failed. A fatal error occurred.";
break;
case 5:
message = "Format ended by user.";
break;
default:
message = "Format failed. ExitCode = " + this.formatProc.ExitCode;
break;
}
this.formatProc.Dispose();
MessageBox.Show(message);
}