我想運行幾個程序由一個一個的,但有時我想保留自己的控制檯窗口打開查看消息/錯誤運行外部進程,等待程序結束,獲取exitcode並保持控制檯打開?
是否有可能運行cmd.exe /K anotherProgram.exe
,等到anotherProgram完成(WaitForExit()
)並獲得另一個程序的exitCode?或者,也許我可以保持控制檯以其他方式打開,而不是從cmd /K
運行它?
我想運行幾個程序由一個一個的,但有時我想保留自己的控制檯窗口打開查看消息/錯誤運行外部進程,等待程序結束,獲取exitcode並保持控制檯打開?
是否有可能運行cmd.exe /K anotherProgram.exe
,等到anotherProgram完成(WaitForExit()
)並獲得另一個程序的exitCode?或者,也許我可以保持控制檯以其他方式打開,而不是從cmd /K
運行它?
您可以捕獲控制檯程序的輸出和errorstream得到消息/錯誤。 這樣你也可以得到程序的退出代碼。
看看在Process -class可用的事件:
Process.OutputDataReceived Event ==>用這個來捕獲標準輸出消息
Process.ErrorDataReceived Event ==>用這個來捕獲錯誤消息
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);
}
正如我在評論上面提到的,我不希望捕捉到輸出,但我看到它是唯一的方法,所以我將其標記爲一個答案。謝謝。 – WRonX
你的意思是說,讓控制檯窗口打開,以便用戶可以讀取輸出? – Jodrell
可以捕獲控制檯窗口的輸出,因此您不需要保持打開狀態。 – Koen
是的,我想保持控制檯窗口打開,因爲我認爲它需要更少的代碼比捕獲輸出並將其呈現在某處。 – WRonX