将运行过程输出重定向到 TextBox

将运行过程输出重定向到 TextBox

问题描述:

我正在尝试将给定 PID 的任何进程的输出定向到我的表单上的文本框,例如 cmd.exe

I am trying to Direct the output of any Process given the PID to a Textbox on my Form such as cmd.exe

我使用以下代码,但没有任何反应:

I use the following code but nothing is happening:

public partial class FormMain : Form
{
    private Int32 PID = 0;
    private Process process;

    public FormMain()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        PID = Convert.ToInt32(textBox2.Text);

        process = Process.GetProcessById(PID);

        process.OutputDataReceived += process_OutputDataReceived;
    }

    void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
    {
        textBox1.Text += e.Data;
    }

    private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
    {
        process.OutputDataReceived -= process_OutputDataReceived;
    }
}

我做错了什么?

我认为您尝试做的事情的问题在于您使用事件的方式.该事件仅在异步输出操作期间触发.

I think the problem with what you are trying to do is with the way you are using the event. The event only fires during async output operations.

您必须设置:

process.StartInfo.RedirectStandardOutput = true;

然后使用将触发事件的异步读取操作:

Then use async read operations which will fire the event:

process.BeginOutputReadLine();

您应该阅读该事件的文档:

You should read the documentation for that event:

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.outputdatareceived.aspx