2

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

What am I doing wrong?

John
  • 45
  • 6

1 Answers1

0

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.

You must set:

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

Ashigore
  • 4,618
  • 1
  • 19
  • 39