Warm tip: This article is reproduced from serverfault.com, please click

c#-跟踪侦听器以写入文本框(WPF应用程序)

(c# - Trace listener to write to a text box (WPF application))

发布于 2009-09-07 12:46:36

对于我的WPF应用程序,我确实使用TextWriterTraceListener记录到文本文件。如何将“跟踪”输出显示到文本框?

Questioner
kjv
Viewed
11
nos 2010-01-22 01:15:04

我将其用于C#winforms,应该可以轻松地将其调整为wpf

public class MyTraceListener : TraceListener
{
    private TextBoxBase output;

    public MyTraceListener(TextBoxBase output) {
        this.Name = "Trace";
        this.output = output;
    }


    public override void Write(string message) {

        Action append = delegate() {
            output.AppendText(string.Format("[{0}] ", DateTime.Now.ToString()));
            output.AppendText(message); 
        };
        if (output.InvokeRequired) {
            output.BeginInvoke(append);
        } else {
            append();
        }

    }

    public override void WriteLine(string message) {
        Write(message + Environment.NewLine);
    }
}

像这样使用

TraceListener debugListener = new MyTraceListener (theTextBox);
Debug.Listeners.Add(debugListener);
Trace.Listeners.Add(debugListener);

记住要跟踪/Debug.Listeners.Remove(debugListener); 当你不再需要它时。