如何在应用程序中显示 cmd 的输出?

How to display the output from cmd in application?

我需要在 c# 中启动一个 cmd 命令,例如:Echo Test.

接下来我想在这样的消息框中显示 CMD 的输出:

MessageBox.Show(output_of_cmd_command);

可能吗?如果可以,怎么做?

这将包括几个步骤:

  • 使用正确的参数启动 CMD 进程
  • 捕获 CMD 输出
  • 在消息框显示

我最近用这个功能为 Python 做了一些事情:

请记住,我通过设置 UseShellExecuteCreateNoWindow 明确抑制了 CMD 对话框本身。如果你愿意,你可以改变这些。

private string RunCommand(string fileName, string args)
{
    ProcessStartInfo start = new ProcessStartInfo();
    start.FileName = fileName;
    start.Arguments = string.Format("{0}", args);
    start.RedirectStandardOutput = true;
    start.RedirectStandardError = true;
    start.UseShellExecute = false;
    start.CreateNoWindow = true;
    
    var sb = new StringBuilder();
    using (Process process = new Process())
    {
        process.StartInfo = start;
        process.OutputDataReceived += (sender, eventArgs) =>
        {
            sb.AppendLine(eventArgs.Data); //allow other stuff as well
        };
        process.ErrorDataReceived += (sender, eventArgs) => {
        };

        if (process.Start())
        {
            process.EnableRaisingEvents = true;
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            process.WaitForExit();
            //allow std out to be flushed
            Thread.Sleep(100);
        }
    }
    return sb.ToString();
}

用法:

var result = RunCommand("path to your cmd.exe", "/C c:\example.bat");
MessageBox.Show(result);

这是 CMD 选项的列表:

Starts a new instance of the Windows command interpreter

CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF]
    [[/S] [/C | /K] string]

/C      Carries out the command specified by string and then terminates
/K      Carries out the command specified by string but remains
/S      Modifies the treatment of string after /C or /K (see below)
/Q      Turns echo off
/D      Disable execution of AutoRun commands from registry (see below)
/A      Causes the output of internal commands to a pipe or file to be ANSI
/U      Causes the output of internal commands to a pipe or file to be
        Unicode
/T:fg   Sets the foreground/background colors (see COLOR /? for more info)
/E:ON   Enable command extensions (see below)
/E:OFF  Disable command extensions (see below)
/F:ON   Enable file and directory name completion characters (see below)
/F:OFF  Disable file and directory name completion characters (see below)
/V:ON   Enable delayed environment variable expansion using ! as the
        delimiter. For example, /V:ON would allow !var! to expand the
        variable var at execution time.  The var syntax expands variables
        at input time, which is quite a different thing when inside of a FOR
        loop.
/V:OFF  Disable delayed environment expansion.