将运行过程输出重定向到 TextBox [英] Redirect Running Process Output to TextBox

查看:46
本文介绍了将运行过程输出重定向到 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

这篇关于将运行过程输出重定向到 TextBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆