Search code examples
c#winformsiowindows-consoletextwriter

Custom textwriter for Console outputstream not working in external classes


I'm trying to forward the Console output to a Windows Forms TextBox control. So I attached a custom TextWriter to the Console which appends the output to the TextBox.

But I think the TextWriter or TextBox is inaccessible from within an external class. How to fix this? Check my code below:

partial class Form1 : Form
{
  public StringWriter _TextWriter;

  public Form1()
  {
    InitializeComponent();

    this._TextWriter = new TextBoxStreamWriter(this.textBox1);
    Console.SetOut(this._TextWriter);

    Console.WriteLine("This text does appear in the TextBox, works perfect.");

    Test ConsoleOutputExternalClass = new Test();
  }
}

public class TextBoxStreamWriter : StringWriter
{
  TextBox _output = null;

  public TextBoxStreamWriter(TextBox output)
  {
    this._output = output;
  }

  public override void WriteLine(string value)
  {
    base.WriteLine(value);
    this._output.AppendText(value.ToString());
  }

  public override Encoding Encoding
  {
    get
    {
      return Encoding.UTF8;
    }
  }
}

private class Test
{
  public Test()
  {
    // HERE I GET AN EXCEPTION ERROR !!
    Console.WriteLine("System.IO.IOException: 'The handle is invalid.'");
  }
}

Solution

  • As I found out after experimenting, the problem had another cause than I expected. In my program I used Console.Clear() to remove all printed lines, but apparently this also destroys the link to the custom set output stream.

    And this wouldn't clear the TextBox after all, I should be using TextBox.Clear().

    I'm sorry for this, because my question is not to the point in this case, the problem appeared to lie somewhere else. In fact, the code in my question does work perfectly because there is no call to Console.Clear(), but I just didn't find out what really caused the problem yet.

    The real question would be: how to "override" Console.Clear() in order to clear the TextBox? But this is for another topic.