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

标签 c# wpf textbox trace listener

对于我的 WPF 应用程序,我使用 TextWriterTraceListener 记录到一个文本文件。我还可以如何将 Trace 输出显示到文本框?

最佳答案

我将其用于 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);当您不再需要它时。

关于c# - 跟踪监听器以写入文本框(WPF 应用程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1389264/

相关文章:

c# - 无法在 Windows 10 中使用 DataTransferManager 共享图像

c# - 使用 Microsoft Identity 和构建解决方案时出现警告 CS1702

c# - 从C#中的文本框获取html标签

javascript - 使用 javascript 或 appscript 独特地添加/删除动态文本框

c# - 将大类分成小类

c# - 在 Xamarin 中将内容页面转换为导航页面

c# - 如何在不更改主机文件的情况下阻止对特定站点的访问,直到重新启动?

wpf - 为什么我的 TabControl 忽略了我的 ItemsPanelTemplate?

c# - 从 .Net 中的 Google Drive API 获取修订历史记录

c# - 如何删除 Windows 10 UWP 应用中 TextBox 控件的默认 "Paste"上下文菜单条目?