8

I am writing an application in C# that at some point starts an application as a child process using the Process class with Asynchronous IO redirection as shown below:

private void AppLaunch_Click(object sender, RoutedEventArgs e)
{

  Process appProcess = new Process();
  appProcess.StartInfo.FileName = currAppPath;
  appProcess.StartInfo.Arguments = "";

  //Setup Redirection
  appProcess.StartInfo.UseShellExecute = false;
  appProcess.StartInfo.ErrorDialog = false;
  appProcess.StartInfo.RedirectStandardError = true;
  appProcess.EnableRaisingEvents = true;
  // Attach Output Handler
  appProcess.ErrorDataReceived += appProc_DataReceived;
  appProcess.Exited += appProc_Exited;
  buildLogConsoleOutputTxtbox.AppendText(currAppPath + "\n");

  appProcess.Start();
  appProcess.BeginErrorReadLine();

}
private void appProc_DataReceived(object sender, DataReceivedEventArgs e)
{
  if (!String.IsNullOrEmpty(e.Data))
  {
    this.appendLogText(e.Data);
  }
}

private void appProc_Exited(object sender, System.EventArgs e)
{
  Process proc = (Process)sender;
  // Wait a short while to allow all console output to be processed and appended
  Thread.Sleep(40);
  this.appendLogText("\n>>");
  proc.Close();
}

private void appendLogText(string logText)
{
  // Use a delegate if called from a different thread,
  // else just append the text directly
  if (buildLogConsoleOutputTxtbox.Dispatcher.CheckAccess())
  {
    // Thread owns the TextBox
    buildLogConsoleOutputTxtbox.AppendText(logText + Environment.NewLine);
  }
  else
  {
    //Invocation Required
    appendLogCallBack appendLog = new appendLogCallBack(buildLogConsoleOutputTxtbox.AppendText);
    buildlogScrollEnd buildlogscrl = new buildlogScrollEnd(buildLogConsoleOutputTxtbox.ScrollToEnd);
    buildLogConsoleOutputTxtbox.Dispatcher.BeginInvoke(appendLog, new object[] { logText + Environment.NewLine });
    buildLogConsoleOutputTxtbox.Dispatcher.BeginInvoke(buildlogscrl);
  }

The Problem with this piece of code is that while I do get the stderr redirected properly to my textbox, This redirection seems to hide the process' stdout output, which I don't want redirected!

If I redirect stdout, I can see it redirected properly, but is it impossible to just redirect stderr and not stdout? I have looked around and googled regarding this topic but all discussions seem to be regarding redirecting stdout ... such as this : How to asynchronously read the standard output stream and standard error stream at once

I would be grateful for any help regarding this!

4

1 回答 1

2

这是不可能的 - 输出和错误句柄同时重定向。MSDN 文章STARTUPINFO描述了STARTF_USESTDHANDLES标志。

但有一个好消息。保留子进程输出仍然是可能的。你只需要:

  • 重定向子进程输出
  • 附加到子进程控制台
  • 将子进程输出写回其控制台

所以在进程开始调用之后

[DllImport("Kernel32.dll", SetLastError = true) ]
static extern uint AttachConsole(int pid);

然后在您的DataReceived处理程序中使用简单的 Console.WriteLine。

于 2012-10-16T21:49:07.430 回答