1

是否可以在VB.NETDebug.Writeline中流式传输和/或Console.Writeline传输到 RichTextBox 控件?

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

4

1 回答 1

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

于 2012-09-10T22:39:01.053 回答