How can I redirect process output (console) to richtextbox?

WaitForExit() blocks your UI Thread, so you don’t see the new output.
Either wait for the process in a separate thread or replace WaitForExit() with something like this:

while (!sortProcess.HasExited) {
     Application.DoEvents(); // This keeps your form responsive by processing events
}

In your SortOutputHandler, you can now directly append output to your textbox. But you should remember to check if you need to invoke it on the UI Thread.

You can check if it’s on the UI thread this way in your handler:

    if (richTextBox1.InvokeRequired) { richTextBox1.BeginInvoke(new DataReceivedEventHandler(SortOutputHandler), new[] { sendingProcess, outLine }); }
    else {
        sortOutput.Append(Environment.NewLine + "[" + numOutputLines.ToString() + "] - " + outLine.Data);
        richTextBox1.AppendText(sortOutput.ToString());
    }

Leave a Comment