事件捕获进程输出

事件捕获进程输出

本文介绍了通过 OutputDataReceived 事件捕获进程输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to capture process output in "realtime" (while it's running). The code I use is rather simple (see below). For some strange reason the OutputDataReceived event is never called. Why?

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...
    }

推荐答案

需要拨打

mProcess.BeginOutputReadLine();

BeginOutputReadLine - "开始异步读取操作应用程序的重定向 StandardOutput 流."

BeginOutputReadLine - "Begins asynchronous read operations on the redirected StandardOutput stream of the application."

这篇关于通过 OutputDataReceived 事件捕获进程输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 21:30