重定向控制台应用程序的标准输出

时间:2016-12-25 09:32:53

标签: c# class events process io-redirection

我在使用该类时遇到问题 Redirecting standard input of console application

我可以执行控制台应用程序

var proc = new ConsoleAppManager("calc.exe");
proc.ExecuteAsync();

但是如何从控制台应用程序接收输出?我想我必须使用StandartTextReceived事件,但我不知道究竟是怎么回事。有人可以给我一个示例代码来接收RichTextBox中的输出吗?

1 个答案:

答案 0 :(得分:0)

您确实需要订阅该StandartTextReceived个活动。以下是如何通过button_click事件执行此操作的示例:

// class member on the form
ConsoleAppManager cm = null;    

private void button1_Click(object sender, EventArgs e)
{
    // check if have an instance, to prevent starting too much
    if (cm == null)
    {
        cm = new ConsoleAppManager(@"cmd.exe");
    } else
    {
        if (cm.Running)
        {
            // still running, bail out
            return; 
        }
    }
    // subscribe to the event
    // the implementation of the ConsoleAppManager handles UI thread sync
    cm.StandartTextReceived += (s, text) =>
    {
        // it doesn't play nicely if the form
        // closes while the process is still running
        if (!this.richTextBox1.IsDisposed)
        {
            this.richTextBox1.AppendText(text);
        }
    };
    cm.ExecuteAsync(@"/c ""dir c:\*.exe /s """);
}

// it is very limited to end it ...
private void Form3_FormClosed(object sender, FormClosedEventArgs e)
{
    if (cm != null)
    {
        // how on earth do you end that process?
        cm = null; 
    }
}