2013-01-07 101 views
6

可能重複:
How do I show console output/window in a forms application?輸出寫入到控制檯從C#WinForms應用程序

是否有一個C#的WinForms程序寫入到控制檯窗口的方法嗎?

+2

尼斯後,但它已經在這裏問:http://stackoverflow.com/questions/4362111/how-do-i-show-console-output-window-in-a-forms-application –

+1

@RobertHarvey:除非我錯過了一些東西,那篇文章沒有解決重定向問題...... – cedd

+0

什麼重定向問題?你在這個問題上沒有提到任何有關這方面的事情。啊,我明白了;你自我回答。那麼,除非你希望別人提供額外的答案...... –

回答

15

基本上有兩件事情可以在這裏發生。

  1. 控制檯輸出

可能的是一個WinForms程序本身附加到(如果需要或到不同的控制檯窗口中,或實際上對新控制檯窗口)創建它的控制檯窗口。一旦連接到控制檯窗口Console.WriteLine()等按預期工作。這種方法的一個問題是,程序立即將控制權交還給控制檯窗口,然後繼續寫入,以便用戶也可以在控制檯窗口中輸入。你可以用/ wait參數來處理這個問題。

Link to start Command syntax

  • 重定向控制檯輸出
  • 這是當某人管從你的程序的其他地方,例如,輸出。

    yourapp> file.txt的

    附加到控制檯窗口在這種情況下有效地忽略了管道。爲了使這個工作,你可以調用Console.OpenStandardOutput()來獲取輸出應該被傳送到的流的句柄。這僅適用於輸出爲管道的情況,所以如果要處理兩種場景,則需要打開標準輸出並寫入並附加到控制檯窗口。這確實意味着輸出被髮送到管道的控制檯窗口,但它是我能找到的最佳解決方案。在我用來做這件事的代碼下面。

    // This always writes to the parent console window and also to a redirected stdout if there is one. 
    // It would be better to do the relevant thing (eg write to the redirected file if there is one, otherwise 
    // write to the console) but it doesn't seem possible. 
    public class GUIConsoleWriter : IConsoleWriter 
    { 
        [System.Runtime.InteropServices.DllImport("kernel32.dll")] 
        private static extern bool AttachConsole(int dwProcessId); 
    
        private const int ATTACH_PARENT_PROCESS = -1; 
    
        StreamWriter _stdOutWriter; 
    
        // this must be called early in the program 
        public GUIConsoleWriter() 
        { 
         // this needs to happen before attachconsole. 
         // If the output is not redirected we still get a valid stream but it doesn't appear to write anywhere 
         // I guess it probably does write somewhere, but nowhere I can find out about 
         var stdout = Console.OpenStandardOutput(); 
         _stdOutWriter = new StreamWriter(stdout); 
         _stdOutWriter.AutoFlush = true; 
    
         AttachConsole(ATTACH_PARENT_PROCESS); 
        } 
    
        public void WriteLine(string line) 
        { 
         _stdOutWriter.WriteLine(line); 
         Console.WriteLine(line); 
        } 
    } 
    
    +0

    謝謝,這是一個很好的解決方案! –

    +0

    您可以讀取命令行選項來指定是寫入標準輸出還是控制檯 – JoelFan

    相關問題