user1907700
user1907700

Reputation:

What is a good way to direct console output to Text-box in Windows Form?

In C#, what is a good way to direct console output to Text-box in Windows Form?

If I have an existing program that has console.WriteLine , do I need to overload the function in Windows Form Text-box?

Upvotes: 4

Views: 15938

Answers (2)

Algirdas
Algirdas

Reputation: 675

Create a text writer which writes to a text box:

    public class TextBoxWriter : TextWriter
    {
        TextBox _output = null;

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

        public override void Write(char value)
        {
            base.Write(value);
            _output.AppendText(value.ToString());
        }

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

And redirect Console output to this writer:

        //...

        public Form()
        {
            InitializeComponent();
        }

        private void Form_Load(object sender, EventArgs e)
        {
            Console.SetOut(new TextBoxWriter(txtConsole));
            Console.WriteLine("Now redirecting output to the text box");
        }

Upvotes: 14

Tommy
Tommy

Reputation: 583

button_Click(object sender, EventArgs e)
{
   try
   {
      // Do stuff
   }
   catch(Exception exception)
   {
      // Couldn't do stuff. Log the exception.
      myTextBox.Text += "\n" + exception.Message;
   }
}

That ought to do it.

Upvotes: -3

Related Questions