运行外部进程,等待程序结束,获取exitcode并保持控制台打开?

时间:2013-09-26 07:24:59

标签: c# process cmd

我想逐个运行几个程序,但有时我想让他们的控制台窗口保持打开以查看消息/错误

是否有可能运行cmd.exe /K anotherProgram.exe,等待另一个程序完成(WaitForExit())并获取另一个程序的exitCode?或者我可以通过其他方式打开控制台,而不是从cmd /K运行它?

1 个答案:

答案 0 :(得分:1)

您可以捕获控制台程序的输出和errorstream以获取消息/错误。 这样你就可以得到程序的退出代码。

查看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);
}