美文网首页
C#中使用命令行并展示实时结果

C#中使用命令行并展示实时结果

作者: _emo_ | 来源:发表于2018-12-24 22:51 被阅读0次

    小声哔哔: 工作中需要做一个桌面程序用于其他服务的统一管理(此项目暂时还未在生产环境使用docker), 所以需要在程序中用到命令行工具. 在网上各种搜帖, 所以在此做个记录, 仅做备忘使用. 因参考的大佬帖子较多, 故在此不一一列出, 见谅.

    以下是正文 ↓↓↓

    一. 简单的使用命令行(新建一个类, 编写以下方法)

    Console.WriteLine("请输入要执行的命令:");
    string strInput = Console.ReadLine();
    Process p = new Process();
    //(1)设置要启动的应用程序
    p.StartInfo.FileName = "cmd.exe";
    //(2)是否使用操作系统shell启动
    p.StartInfo.UseShellExecute = false;
    //(3)接受来自调用程序的输入信息
    p.StartInfo.RedirectStandardInput = true;
    //(4)输出信息
    p.StartInfo.RedirectStandardOutput = true;
    //(5)输出错误
    p.StartInfo.RedirectStandardError = true;
    //(6)不显示程序窗口
    p.StartInfo.CreateNoWindow = true;
    //(7)启动程序
    p.Start();
    //(8)向cmd窗口发送输入信息
    p.StandardInput.WriteLine(strInput + "&exit");
    p.StandardInput.AutoFlush=true;
    //(9)获取输出信息
    string strOuput = p.StandardOutput.ReadToEnd();
    //(10)等待程序执行完退出进程
    p.WaitForExit();
    p.Close();
    Console.WriteLine(strOuput);
    Console.ReadKey();
    

    以上的程序运行后发现cmd在执行完毕后就被关闭了, 我们不希望如此
    修改以上代码如下:

    Process cmd = null;
    if (cmd == null)
    {
    //创建进程对象 
     cmd = new Process(); 
     ProcessStartInfo startInfo = new ProcessStartInfo();
     //设定需要执行的命令 
     startInfo.FileName = "cmd.exe";
     // [ /C ]表示执行完命令后马上退出 
     startInfo.Arguments = "";  
     //不使用系统外壳程序启动
     startInfo.UseShellExecute = false;  
     //不重定向输入 
     startInfo.RedirectStandardInput = true; 
     //重定向输出  
     startInfo.RedirectStandardOutput = true; 
     //不创建窗口
     startInfo.CreateNoWindow = true;  
     cmd.StartInfo = startInfo;
     // cmd.Start();
    }
    

    这样在执行完命令后就不会关闭了
    命令可以执行了, 但我们得展示命令的输出结果才完美.

    二. 在前端展示

    新建一个WindowsForm项目, 编辑Form内容如下

    public partial class Form1 : Form
    {
        public String isRun = "start";
        CmdUtils cmd = new CmdUtils();
        public Form1()
        {
            InitializeComponent();
            new Thread(new ThreadStart(init)).Start();
        }
        private void init()
        {
            cmd.sendCmd(this);
        }
        
        /* 发送按钮 */
        private void button1_Click(object sender, EventArgs e)
        {
            cmd.shell = textBox1.Text;
        }
    
        /* 终止按钮 */
        private void button2_Click(object sender, EventArgs e)
        {
            //isRun = "";
            cmd.shell = "exit";
            //cmd.Close();
            //Environment.Exit(0);
        }
    
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("关闭窗体后,程序会退出!!", "!!提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                e.Cancel = false;
                System.Environment.Exit(0);
            }
            else
            {
                e.Cancel = true;
            }
        }
    }
    

    在 CmdUtils 类中完成cmd命令调用的方法

    public class CmdUtils
    {
        public String shell = "";
        public void sendCmd(Form1 cmdoom)
        {
            Process cmd = null;
            if (cmd == null)
            {
                cmd = new Process();//创建进程对象  
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = "cmd.exe";//设定需要执行的命令  
                startInfo.Arguments = "";//“/C”表示执行完命令后马上退出  
                startInfo.UseShellExecute = false;//不使用系统外壳程序启动  
                startInfo.RedirectStandardInput = true;//不重定向输入  
                startInfo.RedirectStandardOutput = true; //重定向输出  
                startInfo.CreateNoWindow = true;//不创建窗口  
                cmd.StartInfo = startInfo;
                // cmd.Start();
            }
            if (cmd.Start())//开始进程  
            {
                cmd.StandardOutput.ReadLine().Trim();
                cmd.StandardOutput.ReadLine().Trim();
                while (cmdoom.isRun.IndexOf("start") != -1)
                {
                    if (shell.Length > 0)
                    {
                        cmd.StandardInput.WriteLine(shell);
                        cmd.StandardOutput.ReadLine().Trim();
    
                        cmd.StandardInput.WriteLine("\n");
                        String log = cmd.StandardOutput.ReadLine().Trim();
                        String path = log.Substring(0, 2).ToUpper();
                        updateLog(cmdoom, log);
                        log = "";
                        while (true)
                        {
                            String logm = cmd.StandardOutput.ReadLine().Trim();
                            if (logm.IndexOf(path) != -1)
                            {
                                break;
                            }
                            updateLog(cmdoom, logm + "\n");
                            log += logm;
                        }
                        shell = "";
                    }
                }
                cmd.Close();
                cmd = null;
                return;
            }
            return;
        }
        /* 委托 */
        private delegate void UpdateLog();
    
        private void updateLog(Form1 cmd, String log)
        {
            UpdateLog set = delegate ()
            {
                cmd.richTextBox1.AppendText("\n" + log);
            };
            cmd.Invoke(set);
        }
    
        public void Close()
        {
            this.Close();
        }
    }
    

    最终实现如下图:

    WindowsForm显示命令执行结果.png

    三. 加个彩蛋 ( Wpf中的TextBox或RichTextBox自动滚动到最底端末尾 )

    (1) 设置 RichTextBox 属性

    AutoWordSelection="True" 
    

    (2) 向RichTextBox末尾添加内容并滚定至末尾

    window.richTextBox.AppendText(log);
    window.richTextBox.ScrollToEnd();
    

    相关文章

      网友评论

          本文标题:C#中使用命令行并展示实时结果

          本文链接:https://www.haomeiwen.com/subject/abwtlqtx.html