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

问题描述 投票:0回答:2

我需要在c#中启动一个

cmd
命令,例如:
Echo Test

接下来我想在消息框中显示

CMD
的输出,如下所示:

MessageBox.Show(output_of_cmd_command);

可能吗?如果是的话,怎么办?

c# .net forms messagebox
2个回答
1
投票

这将包括几个步骤:

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

我最近使用这个函数为Python做了一些事情:

请记住,我通过设置

UseShellExecute
CreateNoWindow
明确抑制了 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.

0
投票
       public string ExecuteCommandPromptQuery(string command)           
       {
         string output = "";
        try
        {
            ProcessStartInfo psi = new ProcessStartInfo("cmd.exe");
            psi.Arguments = "/c " + command;
            psi.CreateNoWindow = true;
            psi.RedirectStandardOutput = true;
            psi.UseShellExecute = false;
            //psi.Verb = "runas";
            var cmd = Process.Start(psi);
            output = cmd.StandardOutput.ReadToEnd();
            cmd.WaitForExit();                
        }
        catch(Exception ex) 
        {
            
        }     
        return output;
      }
© www.soinside.com 2019 - 2024. All rights reserved.