我想一个一个地运行几个程序,但有时我想保持他们的控制台窗口打开以查看消息/错误
有没有可能运行cmd.exe /K anotherProgram.exe
,等到另一个程序完成(WaitForExit()
)并获取另一个程序的退出代码?或者,也许我可以以其他方式保持控制台打开,而不是从中运行它cmd /K
?
您可以捕获控制台程序的输出和错误流以获取消息/错误。这样你也可以获得程序的退出代码。
查看Process类中可用的事件:
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);
}