2014-02-27 34 views
0

我遇到了一個奇怪的問題。我已經使用Visual Studio 2012/13在C#中編寫了窗體應用程序。我的應用程序打開一個控制檯應用程序,並在運行時捕獲它的標準和錯誤輸出,然後將該輸出打印到Windows窗體中的文本框中。它曾經工作得很好,但我必須改變一些無意中導致此功能停止工作的東西。RedirectStandardOutput不會觸發,直到控制檯進程結束

它現在只在控制檯應用程序完成並退出後,在Windows窗體中打印控制檯應用程序的輸出。我現在一直對此感到頭痛,並且無所適從。我從Visual Studio 2012升級到2013,但該項目沒有更改,升級或類似的東西,所以我不認爲這是罪魁禍首。任何幫助,將不勝感激!

我相信我有合適的密碼設置爲它在打印捕捉到輸出(這曾經反正工作):

transporterProcess.StartInfo.ErrorDialog = true; 
transporterProcess.StartInfo.UseShellExecute = false; 
transporterProcess.StartInfo.CreateNoWindow = true; 
transporterProcess.StartInfo.RedirectStandardOutput = true; 
transporterProcess.StartInfo.RedirectStandardError = true; 
transporterProcess.EnableRaisingEvents = true; 
transporterProcess.OutputDataReceived += new DataReceivedEventHandler(printOutput); 
transporterProcess.ErrorDataReceived += new DataReceivedEventHandler(printError); 
transporterProcess.Exited += new EventHandler(process_Exited); 

... 

transporterProcess.Start(); 
transporterProcess.BeginOutputReadLine(); 
transporterProcess.BeginErrorReadLine(); 

private void printOutput(object sendingProcess, DataReceivedEventArgs outLine) 
{ 
    if (!String.IsNullOrEmpty(outLine.Data)) 
    { // output is a global StringBuilder object 
     output.Clear(); 
     output.Append(outLine.Data + Environment.NewLine); 
     string update = output.ToString(); 
     updateTextfromStandardOutput = new Thread(new ThreadStart(() => this.ThreadProcSafeStandardOutput(update))); 
     this.updateTextfromStandardOutput.Start(); 
    } 
} 

    private void printError(object sendingProcess, 
     DataReceivedEventArgs outLine) 
    { 
     // pretty much identical to the above code 
    } 

    private void ThreadProcSafeStandardOutput(string update) 
    { 
     this.setText(update); 
    } 

    private void ThreadProcSafeStandardError(string update) 
    { 
     this.setText(update); 
    } 

    private void setText(string text) 
    { 
     if (tbxOutput.InvokeRequired || listViewFilesToTransfer.InvokeRequired) 
     { 
      setTextCallback d = new setTextCallback(setText); 
      tbxOutput.Invoke(d, new object[] { text }); 
     } 
     else 
     { 
      ... 

提前感謝!

+0

你在你的'ProcessStartInfo'對象上設置了'UseShellExecute = false','RedirectStandardOuput = true'和'RedirectStandardError = true'嗎? –

+0

這完全正常。重定向的程序將其輸出寫入內部緩衝區。如果它沒有寫足夠的文本來將緩衝區填滿容量,並且本身不強制緩衝區刷新,那麼在程序退出時,直到緩衝區*有*被刷新,纔會看到任何內容。如果您沒有該程序的源代碼,則無法對此做任何處理。 –

+0

@RichardDeeming對不起,我添加了一些我沒有看到我的問題的代碼。 –

回答

0

我加輸出刷新到調用的應用程序,並解決所建議的@HansPassant的問題,雖然它讓人感覺有點像繃帶一樣,但至少它作品。

0

您需要設置EnableRaisingEvents真正

transporterProcess.EnableRaisingEvents = true; 
+0

對不起,我確實有這個,但我沒有把這一點放在我的示例代碼中。我已經在上面添加了它。謝謝! –

+0

酷:)如何向上箭頭和複選標記? – wizulus

+0

哦,我的意思是說我已經在我的代碼中使用了這一點,並不是說這是針對該問題的解決方案。可悲的是,它仍然損壞:( –

相關問題