2

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

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

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

我究竟做错了什么?

4

1 回答 1

0

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

您必须设置:

process.StartInfo.RedirectStandardOutput = true;

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

process.BeginOutputReadLine();

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

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

于 2013-08-22T18:17:01.537 回答