2010-03-16 61 views
2

MSDN聲明在.NET中可以捕獲進程的輸出同時顯示在控制檯窗口中。同時捕獲並顯示控制檯輸出

正常情況下,當您設置StartInfo.RedirectStandardOutput = true;控制檯窗口保持空白。 由於MSDN網站沒有提供這樣的示例,我想知道是否有人會有樣本或可以指向我的樣本?

當一個進程寫文本到其 標準流,則該文本通常在控制檯上顯示 。通過 重定向標準輸出 流,您可以操縱或抑制進程的輸出 。例如, 可以對文本進行過濾,其格式與 的格式不同,或將輸出寫入 控制檯和指定的日誌文件 。 MSDN

這篇文章是由方式類似於Capture standard output and still display it in the console window。但是那篇文章並沒有以工作樣本結束。

非常感謝,

帕特里克

回答

0

看到這裏的SO這個答案,我貼的代碼的過程中給exec的netstat的輸出流重定向到一個StringBuilder實例。該過程創建一個隱藏的窗口,是不可見的...

您可以通過分別改變值

 
ps.CreateNoWindow = true; <--- Comment this out... 
ps.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; <--- Comment this out... 
+0

問題是,當我把可見的窗口,因爲輸出重定向這將是空白。 謝謝, 帕特里克 – 2010-03-18 15:23:45

+0

@帕特里克:然後...將上面的ps.CreateNoWindow更改爲true,並使ps.WindowStyle隱藏...? – t0mm13b 2010-03-18 17:34:38

+0

嗨湯米,抱歉不明白。我的問題的原因是我喜歡像往常一樣在命令窗口中看到輸出,我希望輸出在字符串變量末尾。 當您使用StartInfo.RedirectStandardOutput = true;控制檯窗口保持空白。它看起來不像往常一樣:) :) – 2010-03-23 02:34:45

1

稍微修改代碼,你可以很容易地使用捕獲所有的消息

Process build = new Process(); 
... 
build.StartInfo.UseShellExecute = false; 
build.StartInfo.RedirectStandardOutput = true; 
build.StartInfo.RedirectStandardError = true; 
build.StartInfo.CreateNoWindow = true; 
build.ErrorDataReceived += build_ErrorDataReceived; 
build.OutputDataReceived += build_ErrorDataReceived; 
build.EnableRaisingEvents = true; 
... 

和創建事件build_ErrorDataReceived

static void build_ErrorDataReceived(object sender, DataReceivedEventArgs e) 
{ 
    string msg = e.Data; 
    if (msg != null && msg.Length > 0) 
    { 
     // in msg you have the line you need! 
    } 
} 

我加小例子

Screencast of the application

Solution Files(VS 2008)

+0

>通常當您設置StartInfo時。RedirectStandardOutput = true;控制檯窗口保持空白。 這就是我不想要的:)我喜歡將結果作爲字符串+控制檯窗口應該看起來像平常一樣,並顯示消息的發生。 謝謝帕特里克 – 2010-03-18 15:21:53