Debug.Writeline和/或Console.Writeline到RichTextBox

时间:2012-09-10 21:29:22

标签: vb.net console richtextbox

是否可以将Debug.Writeline和/或Console.Writeline流式传输到VB.NET中的RichTextBox控件?

如果是这样,最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以创建自己的TextWriter并将Console输出设置为该输出,这意味着您可以拦截任何写入。为了使其更通用,您可以传递一个代理,以便将来支持任何操作,而不仅仅是更新您的RichTextBox

例如:

class InterceptingWriter : TextWriter
{
    TextWriter _existingWriter;
    Action<string> _writeTask;

    public InterceptingWriter(TextWriter existing, Action<string> task)
    {
        _existingWriter = existing;
        _writeTask = task;
    }

    public override void WriteLine(string value)
    {
        // This outputs to the console. Remove it if you only want output to
        // appear in your control
        _existingWriter.WriteLine(value);
        // This calls the delegate you passed in to the constructor, updating 
        // your textbox or anything else that acts upon the string passed in
        _writeTask(value);
    }

    public override Encoding Encoding
    {
        get { throw new NotImplementedException(); }
    }

    // ...other overrides as necessary...
}

在被叫方:

Console.SetOut(new InterceptingWriter(Console.Out, (str) => UpdateMyTextBox(str));

现在,无论何时调用Console.WriteLine,字符串都将输出到控制台,您的UpdateMyTextBox方法也将使用相同的字符串进行调用,从而可以相应地更新UI。

对于Debug输出,您可以编写一个侦听器来执行此操作:

http://msdn.microsoft.com/en-us/library/4y5y10s7.aspx