How to redirect Console and Debug output to your UI

How many times have you been in your test environment trying to understand whats happening with no debugger to call on.
I find this especially frustrating in WPF where binding errors fail silently. Log files are a drag - wouldn't it be cool if you could pipe the console/debug output to somewhere in your UI?

It turns out this is pretty easy. Console output can be redirected to a stream

You can easily subclass TextWriter to pipe the stream output to a textbox for example

            // Instantiate the writer 
            TextWriter _writer = new TextBoxStreamWriter(txtMessage); 
            // Redirect the out Console stream 
            Console.SetOut(_writer); 
            Console.WriteLine("Now redirecting console output to the text box");


    public class TextBoxStreamWriter : TextWriter
    {
        TextBox _output = null;

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

        public override void Write(char value)
        {
            base.Write(value);
            _output.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        _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; }
        }
    }

Undoing what you've done.
            StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
            standardOutput.AutoFlush = true;
            Console.SetOut(standardOutput);

Redirecting debug output is even easier as it offers a lot of flexibility via tracelisteners out of the box

In this example I’m leverging the code from above to send debug output to the console and hence to my textbox

            Debug.Listeners.Add(new TextWriterTraceListener(Console.Out));
            Debug.WriteLine("Now redirecting debug output to the text box");

No comments:

Post a Comment