55

我正在尝试“实时”捕获进程输出(在它运行时)。我使用的代码相当简单(见下文)。由于某些奇怪的原因,从未调用 OutputDataReceived 事件。为什么?

private void button2_Click(object sender, EventArgs e)
    {
      // Setup the process start info
      var processStartInfo = new ProcessStartInfo("ping.exe", "-t -n 3 192.168.100.1")
      {
        UseShellExecute = false,
        RedirectStandardOutput = true
      };

      // Setup the process
      mProcess = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true };

      // Register event
      mProcess.OutputDataReceived += OnOutputDataReceived;

      // Start process
      mProcess.Start();
      mProcess.WaitForExit();
    }

    void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
    {
       //Never gets called...
    }
4

2 回答 2

98

你需要打电话

mProcess.BeginOutputReadLine();

BeginOutputReadLine - “在应用程序的重定向 StandardOutput 流上开始异步读取操作。”

于 2012-07-24T14:00:09.220 回答
2

void ExecuteCommand(string cmdpath, string cmdargs)
{
    string command = cmdpath + " " + cmdargs;

    tabc_results.SelectTab(1); 
    DoConsole("\r\nCmd>> " + command + "\r\n");

    var processInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe", "/c " + command);
    processInfo.CreateNoWindow = true;
    processInfo.UseShellExecute = false;
    processInfo.RedirectStandardError = true;
    processInfo.RedirectStandardOutput = true;

    var process = System.Diagnostics.Process.Start(processInfo);

    process.OutputDataReceived += (
        object sender, System.Diagnostics.DataReceivedEventArgs e
    ) => DoConsole("stdout>>  " + e.Data + "\r\n");
    //Console.WriteLine("output>>" + e.Data);
    process.BeginOutputReadLine();

    process.ErrorDataReceived += (
        object sender, System.Diagnostics.DataReceivedEventArgs e
    ) =>DoConsole("stderr>>  " + e.Data + "\r\n");
    //Console.WriteLine("error>>" + e.Data);
    process.BeginErrorReadLine();

    process.WaitForExit();

    DoConsole("retcode>> " + process.ExitCode.ToString() + "\r\n");
    //Console.WriteLine("ExitCode: {0}", process.ExitCode);
    process.Close();
}
于 2016-01-31T21:03:46.157 回答