Articles in categories

Articles

Start console application and read output in WPF

Method to start an Console Application from WPF and read it's output text in a TextBox. Preferable a multiline TextBox with auto-scrolling.

public void StartProcess()
{
	try
	{
		using (var selProcess = new Process())
		{
			selProcess.StartInfo.FileName = Directory.GetCurrentDirectory() + @"\ConsoleTest.exe";
			selProcess.StartInfo.CreateNoWindow = true;
			selProcess.StartInfo.UseShellExecute = false;
			selProcess.StartInfo.RedirectStandardOutput = true;

			// Event Handler
			selProcess.OutputDataReceived += SortOutputHandler;

			// Start the process
			selProcess.Start();

			// Read output
			selProcess.BeginOutputReadLine();
		}
	}
	catch (Exception ex)
	{
		MessageBox.Show(Application.Current.MainWindow, ex.Message, "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
	}
}

private void SortOutputHandler(object sender, DataReceivedEventArgs e)
{
	Trace.WriteLine(e.Data);
	Dispatcher.BeginInvoke(new Action(() =>
	{
		// LogText is a databount string dp property to a TextBox
		LogText += e.Data + Environment.NewLine;
	}));
}