我遇到了一個奇怪的問題。我已經使用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
{
...
提前感謝!
你在你的'ProcessStartInfo'對象上設置了'UseShellExecute = false','RedirectStandardOuput = true'和'RedirectStandardError = true'嗎? –
這完全正常。重定向的程序將其輸出寫入內部緩衝區。如果它沒有寫足夠的文本來將緩衝區填滿容量,並且本身不強制緩衝區刷新,那麼在程序退出時,直到緩衝區*有*被刷新,纔會看到任何內容。如果您沒有該程序的源代碼,則無法對此做任何處理。 –
@RichardDeeming對不起,我添加了一些我沒有看到我的問題的代碼。 –