重定向cmd.exe输出/输入时丢失最后一行(在C#中)

时间:2011-12-22 22:52:14

标签: c# redirect process cmd

我试图通过C#RichTextArea启动和控制CMD.exe(不是只执行一个命令,而是让它等待下一个用户输入,就像在命令提示符中一样)。似乎工作但它没有重定向输出的最后一行(例如经典"按任意键继续......"执行后或光标前的工作目录)直到我发送另一个输入。这是基本代码:

class CmdPanel : Panel
{
    CmdTextArea textArea;

    Process winCmdProcess;

    public CmdPanel()
    {
        this.BorderStyle = BorderStyle.None;

        textArea = new CmdTextArea(this);
        this.Controls.Add(textArea);

        this.InitializeComponent();
        this.StartShell();
    }

    public void StartShell()
    {
        this.winCmdProcess = new Process();
        this.winCmdProcess.StartInfo.FileName = "cmd.exe";
        this.winCmdProcess.StartInfo.UseShellExecute = false;
        this.winCmdProcess.StartInfo.RedirectStandardOutput = true;
        this.winCmdProcess.StartInfo.RedirectStandardError = true;
        this.winCmdProcess.StartInfo.RedirectStandardInput = true;
        this.winCmdProcess.StartInfo.CreateNoWindow = true;
        this.winCmdProcess.OutputDataReceived += new DataReceivedEventHandler(winCmdProcess_OutputDataReceived);
        this.winCmdProcess.ErrorDataReceived += new DataReceivedEventHandler(winCmdProcess_ErrorDataReceived);

        this.winCmdProcess.Start();
        this.winCmdProcess.BeginOutputReadLine();
        this.winCmdProcess.BeginErrorReadLine();

    }

    /// <summary>
    /// Executes a given command
    /// </summary>
    /// <param name="command"> A string that contains the command, with args</param>
    public void Execute(String command)
    {
        if (!string.IsNullOrWhiteSpace(command))
        {
            this.winCmdProcess.StandardInput.WriteLine(command);
        }
    }

    private void winCmdProcess_OutputDataReceived(object sendingProcess, DataReceivedEventArgs outLine)
    {
        this.ShowOutput(outLine.Data);
    }

    private void winCmdProcess_ErrorDataReceived(object sendingProcess, DataReceivedEventArgs outLine)
    {
        this.ShowOutput(outLine.Data);
    }

    delegate void ShowOutputCallback(string text);
    private void ShowOutput(string text)
    {
        if (this.textArea.InvokeRequired)
        {
            ShowOutputCallback call = new ShowOutputCallback(ShowOutput);
            this.Invoke(call, new object[] { text });
        }
        else
        {
            this.textArea.AppendText(text + Environment.NewLine);
        }
    }

    private void InitializeComponent()
    {

    }

(我没有提供有关textarea的详细信息,但它将新命令发送到Execute方法。)

我错过了什么?

1 个答案:

答案 0 :(得分:1)

事件won't fire unless a newline is output(或直到流关闭或缓冲区被填满),因此部分行或命令提示符不会触发事件。