WPF TextBox Trace Listener

TextBox Trace listener adds a trace output to a text box

Listener
  1. using System;
  2. using System.Diagnostics;
  3. using System.Windows.Controls;
  4.  
  5. namespace PCM.SystemServices.RequestBuilder
  6. {
  7.     public class TextBoxTraceListener : TraceListener
  8.     {
  9.         private TextBox Target;
  10.         private StringSendDelegate InvokeWrite;
  11.  
  12.         public TextBoxTraceListener(TextBox target)
  13.         {
  14.             Target = target;
  15.             InvokeWrite = new StringSendDelegate(SendString);
  16.         }
  17.  
  18.         public override void Write(string message)
  19.         {
  20.             Target.Dispatcher.Invoke(InvokeWrite, new object[] { message });
  21.         }
  22.  
  23.         public override void WriteLine(string message)
  24.         {
  25.             Target.Dispatcher.Invoke(InvokeWrite, new object[] { message + Environment.NewLine });
  26.         }
  27.  
  28.         private delegate void StringSendDelegate(string message);
  29.  
  30.         private void SendString(string message)
  31.         {
  32.             // No need to lock text box as this function will only
  33.             // ever be executed from the UI thread
  34.             Target.Text += message;
  35.         }
  36.     }
  37. }

This class can be used as below:

Usage
  1. private void ReissueSessionKey_Click(object sender, RoutedEventArgs e)
  2.     {
  3.         RequestLog.Clear();
  4.  
  5.         Trace.Listeners.Add(new TextBoxTraceListener(RequestLog));

 

References:

The article below has the WinForms version

http://www.codeproject.com/Articles/21009/A-Simple-TextBox-TraceListener

Advertisements

About vijayvepa

I'm a software consultant for Software Specialists Inc. currently working at Philips Respironics, Pittsburgh

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: