C#程序调用cmd执行多个命令

C#程序调用cmd执行多个命令

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.TextBox commandText;

        Process p;
        // 命令历史记录
        List<string> commandList;
        // 上下切换命令时的下标
        int index;
        public Form1()
        {
            InitializeComponent();
            initProcess();
            commandList = new List<string>();
        }
        // C# 自动生成的代码
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.commandText = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(545, 10);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "按钮";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(12, 39);
            this.textBox1.Multiline = true;
            this.textBox1.Name = "textBox1";
            this.textBox1.ReadOnly = true;
            this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this.textBox1.Size = new System.Drawing.Size(608, 353);
            this.textBox1.TabIndex = 1;
            // 
            // commandText
            // 
            this.commandText.Location = new System.Drawing.Point(12, 12);
            this.commandText.Name = "commandText";
            this.commandText.Size = new System.Drawing.Size(527, 21);
            this.commandText.TabIndex = 2;
            this.commandText.KeyUp += new System.Windows.Forms.KeyEventHandler(this.commandText_KeyUp);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(632, 404);
            this.Controls.Add(this.commandText);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
            this.PerformLayout();

        }
        // 初始化 Process
        private void initProcess() {
            p = new Process();
            // 设置要启动的程序
            p.StartInfo.FileName = "cmd.exe";
            // 设置 参数
            //p.StartInfo.Arguments = "ipconfig";
            // 设置启动为当前项目的子线层
            p.StartInfo.UseShellExecute = false;        //是否使用操作系统shell启动
            p.StartInfo.RedirectStandardInput = true;   //接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardOutput = true;  //由调用程序获取输出信息
            p.StartInfo.RedirectStandardError = true;   //重定向标准错误输出
            p.StartInfo.CreateNoWindow = true;          //不显示程序窗口
            // 为异步获取订阅事件 
            p.OutputDataReceived += new DataReceivedEventHandler(cmdMessage);
            p.ErrorDataReceived += new DataReceivedEventHandler(cmdMessage);
            // 启动
            p.Start();
            // 异步获取命令行内容  
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();
            p.StandardInput.AutoFlush = true;
        }
        private void cmdMessage(object sender, DataReceivedEventArgs e) {
            string data = e.Data;
            //Console.WriteLine(data);
            //this.textBox1.Text += data;
            // 直接设置不是一个线程会报错 需要使用委托类
            setTextBox(data);


        }
        // 设置读取到的消息到textBox1 中
        // 由于是异步 Process 调用此方法设置消息 需要使用委托类
        public void setTextBox(string msg) {
            // 如果不是当前线程 使用委托类
            if (this.textBox1.InvokeRequired)
            {
                // 创建和执行委托类
                this.Invoke(new setMessage(setTextBox), msg);
            }
            else {
                this.textBox1.Text += msg+"\r\n";
            }
        }
        // 执行 cmd命令 
        private void sendCommand(string command) {
            // 如果在startCommand中已经执行了命令 就不在cmd中执行了 
            if (!startCommand(command)) {
                p.StandardInput.WriteLine(command);
            }
            
        }
        //  特殊命令 不需要cmd执行
        private bool startCommand(string command)
        {
            string cmd = command.ToLower();
            if (cmd.Equals("clear") || cmd.Equals("cls"))
            {
                // 清屏命令
                textBox1.Text = "";
                return true;
            }
            return false;
        }

        public delegate void setMessage(string msg);
        // 按钮单击事件 执行命令
        private void button1_Click(object sender, EventArgs e)
        {
            // 需要执行的cmd命令
            string command = this.commandText.Text.Trim();
            if (command.Length > 0) {
                // 执行命令
                sendCommand(command);
                // 吧当前命令添加到历史记录中
                commandList.Add(command);
                index++;
                // 清除命令
                this.commandText.Text = "";

            }
        }
      
        // 键盘事件
        private void commandText_KeyUp(object sender, KeyEventArgs e)
        {
            // 回车事件
            if (e.KeyValue == 13)
            {
                // 执行命令
                button1_Click(null, null);
            }
            // 上下切换历史命令
            else if (e.KeyValue == 38)
            {
                // 上 38
                // ArgumentOutOfRangeException
                if (commandList.Count <= 0 || index <= 0) return;
                index--;
                this.commandText.Text = commandList[index];
                

            }
            else if (e.KeyValue == 40)
            {
                // 下 40
                // 防止下标越界
                if (commandList.Count <= 0 || index >= commandList.Count) return;
                index++;
                this.commandText.Text = commandList[index];
                
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值