c# – Console output in richtextbox C # windows form

Question:

I am trying to render console output in RichTextBox . Here is my code:

public void Run()
{
    Process myProcess = new Process();
    myProcess.StartInfo.FileName = @"start.bat";
    myProcess.StartInfo.CreateNoWindow = true;
    myProcess.StartInfo.UseShellExecute = false;
    myProcess.StartInfo.RedirectStandardOutput = true;
    myProcess.OutputDataReceived += proc_OutputDataReceived;
    myProcess.Start();
    myProcess.BeginOutputReadLine();
}

public void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
   this.Invoke(new Action(() => 
   richTextBoxConsole.Text += (e.Data + Environment.NewLine)));
}

But in the RichTextBox only the first line from the console is displayed. And it is necessary that all lines are displayed in real time. Where is the mistake?

Answer:

in the office of the microsoft documentation there is an almost ready-made solution

https://msdn.microsoft.com/en-us/library/system.diagnostics.process.outputdatareceived.aspx

subscribe to the corresponding event and simply duplicate the text on this event in the required field

Scroll to Top