C# - Creating a Process, reading its console output into a textbox on a form

Post date: Nov 2, 2011 2:38:57 PM

We want to spin of a new process and then capture the output of that process. In this example we need to create a Windows Forms project and place 2 textboxes on the form and also one button.

In the first textbox we we type the name of the executable that we wish to start (and read console output from).

The second textbox will be used to display the results.

The button is of course used to start the process.

using System;using System.Windows.Forms;namespace TestingThreading { /// <summary> /// UI for testing Control panel /// </summary> public partial class TestUserControl : UserControl { /// <summary> /// Constructor duh /// </summary> public TestUserControl() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { System.Diagnostics.ProcessStartInfo testingProcess = new System.Diagnostics.ProcessStartInfo(textBox1.Text); testingProcess.RedirectStandardOutput = true; testingProcess.UseShellExecute = false; System.Diagnostics.Process p = System.Diagnostics.Process.Start(testingProcess); p.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(p_OutputDataReceived); p.BeginOutputReadLine(); } void p_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e) { AppendOutputTextbox(e.Data); } private void AppendOutputTextbox(string data) { if (InvokeRequired) { this.BeginInvoke((Action)delegate() { AppendOutputTextbox(data); }); } else { textBox2.Text += data + Environment.NewLine; } } }}