Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect Debug.WriteLine stream to a textblock

I would like to redirect the Debug stdout stream to a textblock. Is there an easy way to do that ?

Thanks.

like image 349
Matthieu Oger Avatar asked Nov 28 '25 02:11

Matthieu Oger


2 Answers

Add a custom Tracelistener to output you want to listen to.

Here's a simple class which extends TraceListener and takes the TextBox which it is to update in the constructor

class TextBoxTraceListener : TraceListener
{
    private TextBox tBox;

    public TextBoxTraceListener(TextBox box)
    {
        this.tBox = box;
    }

    public override void Write(string msg)
    {
        //allows tBox to be updated from different thread
        tBox.Parent.Invoke(new MethodInvoker(delegate()
        {
            tBox.AppendText(msg);
        }));
    }

    public override void WriteLine(string msg)
    {
        Write(msg + "\r\n");
    }
}

In the Form Code initialise the TextBoxTraceListener after the handle to the Form has been created:

    protected override void OnHandleCreated(EventArgs e)
    {
        TextBoxTraceListener tbtl = new TextBoxTraceListener(TheTextBox);
        Debug.Listeners.Add(tbtl);
        Debug.WriteLine("Testing Testing 123");
    }

Done. If you want to listen to Trace instead of Debug output:

Trace.Listeners.Add(tbtl);
like image 166
wal5hy Avatar answered Nov 30 '25 14:11

wal5hy


Add a TextWriterListener (http://msdn.microsoft.com/en-us/library/system.diagnostics.textwritertracelistener.aspx) to your Debug & have the listener flush it's contents to your text using the resulting stream's ReadToEnd() call.

If that is not available you can implement your own listener for the form & have it output to your textbox. Something like this should do the trick where the form holding your TextBox also implements this TextListener & the textBox is passed into the listener.

class TextListener : TraceListener
{
    private TextBox tBox;

    TextListener( TextBox box)
    {
      this.tBox = box;
    }


    public override void Write(string msg)
    {
       if(box== null) return;

       box.Text += msg;
    }

    public override void WriteLine(string msg)
   {
      if(HandleText == null) return;
      Write(msg);
      box.Text += "\r\n";
   }

}
like image 29
Chris Avatar answered Nov 30 '25 16:11

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!