在C#应用程序中获取实时CMD命令输出

时间:2018-12-30 07:35:02

标签: c# desktop-application

我想创建一个桌面应用程序,例如命令提示符。在该应用程序中,我从文本框获取输入,然后将实时输出放在富文本框上。

但是某些命令需要等待完整执行,例如“ composer install”(这将下载所需的资源,这就是为什么要花费很长时间,并且还会以百分比显示下载的过程状态)

所以我的主要问题是如何执行命令提示符之类的操作,如果没有其他语言(而不是c#)可以给出动态输出,而不会挂起,那么建议我。

我的桌面应用程序看起来像这样。

enter image description here

和单击事件方法上的c#“运行”按钮如下。

private void button1_Click(object sender, EventArgs e)
{
    richTextBox1.Text = "";
    if (textBox1.Text != null)
    {

        ProcessStartInfo info = new ProcessStartInfo("cmd", "/c " + textBox1.Text);

        info.UseShellExecute = false;
        info.RedirectStandardInput = true;
        info.RedirectStandardOutput = true;
        info.RedirectStandardError = true;
        info.CreateNoWindow = true;

        StringBuilder outputBuilder = new StringBuilder();
        StringBuilder errorBuilder = new StringBuilder();

        Process process = new Process();
        process.StartInfo = info;
        process.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);
        process.ErrorDataReceived += new DataReceivedEventHandler(SortOutputHandler);

        process.Start();
        process.BeginErrorReadLine(); // do this after process.Start()
        process.BeginOutputReadLine();

        process.WaitForExit();
    }
}

private void SortOutputHandler(object sendingProcess,DataReceivedEventArgs outLine)
{
    StringBuilder sortOutput = new StringBuilder("");
    if (richTextBox1.InvokeRequired) { richTextBox1.BeginInvoke(new DataReceivedEventHandler(SortOutputHandler), new[] { sendingProcess, outLine }); }
    else
    {
        sortOutput.Append(Environment.NewLine + outLine.Data);
        richTextBox1.AppendText(sortOutput.ToString());
        richTextBox1.ScrollToCaret();
    }
}

我的代码完全可以使用,但是应用程序挂起,直到在运行“ composer install”之类的动态命令时完全执行命令为止。

0 个答案:

没有答案