TraceListener to a textbox

January 16, 2010 by Dave
 

Trace, in System.Diagnostics is useful for determining where an application failed. .NET has build-in support for writing to the console or a file on disk, but it’s a little bit more complicated to direct this output to a TextBox on a windows form.

Here’s the class you need to get the trace information.

    class FormTracer : TraceListener
    {
        public delegate void OnTextHandler(string msg, bool newLine);
        public event OnTextHandler OnText;
 
        public override void Write(string message)
        {
            if (OnText != null)
                OnText.Invoke(message, false);
        }
 
        public override void WriteLine(string message)
        {
            if (OnText != null)
                OnText.Invoke(message, true);
        }
 
        public FormTracer()
        {
            Trace.Listeners.Add(this);
        }
 
         ~FormTracer()
        {
            Trace.Listeners.Remove(this);
        }
    }

When created, FormTracer will add itself to the tracers collection and start receiving messages. To add these messages to your form, create a FormTracer object like so:

        public Form1()
        {
            InitializeComponent();
 
            FormTracer ft = new FormTracer();
            ft.OnText += new FormTracer.OnTextHandler(ft_OnText);
        }

The event handler may be called on threads outside the UI, so you’ll want to make the OnText handler look something like this

        void ft_OnText(string msg, bool newLine)
        {
            if (this.IsHandleCreated)
            {
                this.Invoke((MethodInvoker)delegate()
                {
                    textBox1.Text += msg;
                    if (newLine) textBox1.Text += "\r\n";
                });
            }
        }

Add a button and handle the Click event for a test Trace message.

          private void button1_Click(object sender, EventArgs e)
        {
            Trace.WriteLine("Button Pressed!");
        }

Comments