Monday, December 5, 2011

Redirect console output to textbox

When creating any application debugging is always very important and to do that we always need lots of messages to understand the state of our program.
In console application it is customary to output text messages on the terminal either through printing or assertions, but in windows application that is not very practical.
We could show window messages but that doesn't work very well.
It would be much better to show the error and state messages on a standard textbox. That would require the textbox to be accessible from all classes which would mess the flow of the code.
It is much better to redirect the console output to a textbox and always output on the console which is always accessible.

To do that we need to inherit the StringWriter class and create a new TextBoxStreamWriter class :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace Emgu_Tracker_Advanced_V2.Source
{
    /// <summary>
    /// Use this method to redirect stream of text output to textbox
    /// </summary>
    public class TextBoxStreamWriter :StringWriter
    {
        #region Properties
        private TextBox textBoxOutput;
        protected StreamWriter writer;
        protected MemoryStream mem;
        #endregion

        #region Constructor
        public TextBoxStreamWriter(TextBox _output) 
        {
            textBoxOutput = _output;
            mem = new MemoryStream(1000000);
            writer = new StreamWriter(mem);
            writer.AutoFlush = true;
        }
        #endregion

        #region Override Mathods
        // override methods
        public override void Write(char value)
        {
            base.Write(value);
            textBoxOutput.AppendText(value.ToString());
            writer.Write(value);
        }

        // override methods
        public override void Write(string value)
        {
            base.Write(value);
            textBoxOutput.AppendText(value.ToString());
            writer.Write(value);
        }

        public override void WriteLine(string value)
        {
            base.WriteLine(DateTime.Now.ToString(value));
            textBoxOutput.AppendText(value.ToString() + Environment.NewLine);
            writer.Write(value);
        }
        #endregion
    }
}


Then inside your application it is very easy to redirect the console output :

            #region Redirect Text Output
            streamTextBoxWriter = new TextBoxStreamWriter(textBoxMessages);
            System.Console.SetOut(streamTextBoxWriter);
            #endregion

Now every time you output to console it is displayed on the textbox you used in the streamTextBoxWriter constructor.