在 C# 中处理打印到控制台事件句柄

Process print to console event handle in C#

我有两个控制台应用程序,第一个是"Process1",它编译为一个exe,不能更改其中的代码。 第二个是 "meter" 控制台应用程序,用于计算 Process1 的启动时间。我要现在的时刻 当控制台打印 HelloWorld 时 windows.

// {我的流程1}: //我把它编译成了一个叫process1.exe.

的程序集
Class Process1{
    static void Main(String[] args]){
        Console.Write("Hello word");
    }
}

我的第二个应用程序是一个控制台应用程序,它调用 process1.exe 作为进程,我想知道什么时候 process1 是 "ready",假设它是打印 "Hello Word" 的时间。我读到了 Process.OutputDataReceived 事件, 但是在调试时事件永远不会被触发,里面的代码永远不会打印出来。

// {仪表应用}

public Class Student{
    String ID;
    String Name;
}

public Class Program{
    public static void Main(String[] args){
        p.StartInfo = new ProcessStartInfo("process1.exe")
        {
            UseShellExecute = false,
            //Add this line
            RedirectStandardOutput = true,
        };
        Student st = new Student();
        p.OutputDataReceived += P_OutputDataReceived;
        p.Start();
        //Add this line
         p.BeginOutputReadLine();
        p.WaitForExit();
    }

    private static void P_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            string output = e.Data;
            Console.WriteLine("Process1 ready at: "+DateTime.Now);
            Console.WriteLine("Data is: " + output);

        }

}

我的评论总结:

这个对Main()方法的修改应该可以做到。

public static void Main(String[] args){
    p.StartInfo = new ProcessStartInfo("process1.exe")
    {
        UseShellExecute = false,
        RedirectStandardOutput = true
    };
    Student st = new Student();
    p.OutputDataReceived += P_OutputDataReceived;
    p.Start();
    p.BeginOutputReadLine();
    p.WaitForExit();
}