0

In my application I am trying to show the output of the console into a win forms textbox. This is working as long as I am in the gui thread. But when I write to the console from an other thread, I get an InvalidOperationException. This is the code i use:

in form:

public partial class Form1 : Form
    {
        Crawler crawler = new Crawler();
        Log log = null;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            log = new Log(tbLogOutput);    
            Console.SetOut(log);
        }
    }
}

In the Textwriter:

class Log : TextWriter
    {
        TextBox _output = null;

        public Log(TextBox output)
        {
            _output = output;
        }

        public override void Write(char value)
        {
            base.Write(value);
            _output.AppendText(value.ToString()); // When character data is written, append it to the text box.
        }

        public override Encoding Encoding
        {
            get { return System.Text.Encoding.UTF8; }
        }
    }
R.hagens
  • 325
  • 4
  • 19

1 Answers1

0

Might be worth typing into Google "Update UI from thread c#"

How to update the GUI from another thread in C#?

Community
  • 1
  • 1
Scott Perham
  • 2,410
  • 1
  • 10
  • 20