在事件处理程序中打印进程的标准输出



我有一个控制台应用程序,我正在从我的 C# 程序作为进程运行。
我已经制作了一个事件处理程序,以便在此过程终止时调用。
如何在事件处理程序中打印此过程的标准输出。基本上,如何访问事件处理程序中进程的属性?
我的代码如下所示。

public void myFunc()
{
.
.
Process p = new Process();
p.StartInfo.FileName = "myProgram.exe";
p.StartInfo.RedirectStandardOutput = true;
p.EnableRaisingEvents = true;
p.Exited += new EventHandler(myProcess_Exited);
p.Start();
.
.
}
private void myProcess_Exited(object sender, System.EventArgs e)
{
    Console.WriteLine("log: {0}", <what should be here?>);
}

我不想将进程对象 p 作为类的字段。

另外,System.EventArgs e字段有什么用?如何使用?

在事件处理程序中

object sender

是 Process 对象(在整个 .NET Framework 中,这是一种非常常见的模式)

Process originalProcess = sender as Process;
Console.WriteLine("log: {0}", originalProcess.StandardOutput.ReadToEnd());

另请注意,您必须设置:

p.StartInfo.UseShellExecute = false;

以在进程中使用 IO 重定向。

像这样使用:

private void myProcess_Exited(object sender, System.EventArgs e)
{
    Process pro = sender as Process; 
    string output = pro.StandardOutput.ReadToEnd()
    Console.WriteLine("log: {0}", output);
}

Standart 输出不是别的,而是 StreamReader。

一种选择是在闭包中捕获它:

public void myFunc()
{
    Process p = new Process();
    p.StartInfo.FileName = "myProgram.exe";
    p.StartInfo.RedirectStandardOutput = true;
    p.EnableRaisingEvents = true;
    p.Exited += new EventHandler((sender, args) => processExited(p));
    p.Start();
}
private void processExited(Process p)
{
    Console.WriteLine(p.ExitTime);
}

最新更新