2012-09-10 34 views
1

是否有可能將Debug.Writeline和/或Console.Writeline流式傳輸到VB.NET中的RichTextBox控件?Debug.Writeline和/或Console.Writeline到RichTextBox

如果是這樣,那麼最好的方法是什麼?

+0

是控制檯/調試調用同一應用程序在RichTextBox內製成,或者是你想加載控制檯應用程序,並希望在RTB中顯示其輸出? –

+0

來自同一個應用程序。 –

+0

然後這個鏈接可以幫助你將你的console.stdout重定向到另一個流,然後你可以將它們傳送到你的RTB中:http://msdn.microsoft.com/en-us/library/system.console.setout.aspx –

回答

1

您可以創建自己的TextWriter並將Console輸出設置爲該值,這意味着您可以截取任何Writes。爲了使其更通用化,您可以傳入代表,以便將來可以支持任何操作,而不僅僅是更新您的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方法也將與被叫相同的字符串,讓你相應地更新用戶界面。

對於Debug輸出,你可以寫一個監聽器要做到這一點:

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

+0

對不起,對於C#代碼。我錯過了這個問題被標記爲VB.NET。您可以使用在線轉換器爲您翻譯它:http://www.developerfusion.com/tools/convert/csharp-to-vb/ –

+0

我已經嘗試將此轉換爲vb.net,但我無法修復它。你怎麼稱呼它? – LuckyLuke82