重定向cmd.exe输出/输入时缺少最后一行(在c#中)

本文关键字:一行 最后 输出 exe cmd 输入 重定向 | 更新日期: 2023-09-27 18:18:34

我试图通过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方法。)

我错过了什么?

重定向cmd.exe输出/输入时缺少最后一行(在c#中)

该事件不会触发,除非输出换行符(或直到流关闭或缓冲区被填满),因此部分行或命令提示符不会触发该事件。