If you redirect Console.Out to an instance of StringWriter , you can get the text that was written to the console:
StringWriter writer = new StringWriter(); Console.SetOut(writer); StringBuilder consoleOut = writer.GetStringBuilder(); string text = consoleOut.ToString();
If you do this in the new Form , you can then poll at intervals to get the text that has been written to the console so far and put its value in the TextBox . A rough example:
public MyForm() { InitializeComponent(); StringWriter writer = new StringWriter(); Console.SetOut(writer); Timer timer = new Timer(); timer.Tick += (o, s) => textBox.Text = writer.GetStringBuilder().ToString(); timer.Interval = 500; timer.Start(); }
A few things to watch out for:
StringWriter is one-time, so technically you need to dispose of it when it is done (although in fact its Dispose() method does nothing that is not a big problem).StringWriter stores an internal StringBuilder containing all the text written so far on it. Over time, this will only increase, so the longer your application runs, the more memory it will consume. You can put some checks to periodically clean it when it reaches a certain size.- If you make the interval too short, you will constantly use the CPU.
- Be sure to set
Console.Out back to its original value when you close the form, otherwise you wonβt be able to print messages to the console again.
source share