Redirect Debug.WriteLine stream to a textblock

人盡茶涼 提交于 2019-12-13 15:13:33

问题


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

Thanks.


回答1:


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);



回答2:


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";
   }

}



回答3:


It seems there is no solution for WP7. I guess I must wait the next version.



来源:https://stackoverflow.com/questions/10950732/redirect-debug-writeline-stream-to-a-textblock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!