C# 动态执行Dos命令并显示输出命令执行结果

本文以一个简单的小例子讲解如何将命令行信息实时的输出到文本框中。仅供学习分享使用,如有不足之处,还请指正。

概述

在C#程序开发过程中,有时需要运行其它的程序并获得输出的结果来进行进一步的处理。一般第三方的程序,主要通过进程来调用,如果能够获取第三方程序执行过程中的信息,就显得方便而有用。

涉及知识点:

  •  进程相关类: Process,ProcessStartInfo,主要设置进程的重定向输出,以及接受数据的事件。
  •  文本框操作:多行显示,滚动条总在最下面

效果图

如下【如果命令执行完毕,会自动结束,如果中断进程,可以手动点击结束进程】:

核心代码

主要代码如下:

复制代码
复制代码
  1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Diagnostics;
  6 using System.Drawing;
  7 using System.Linq;
  8 using System.Runtime.InteropServices;
  9 using System.Text;
 10 using System.Threading;
 11 using System.Threading.Tasks;
 12 using System.Windows.Forms;
 13 
 14 namespace DemoBat
 15 {
 16     public partial class MainForm : Form
 17     {
 18         private BatStatus curBatSataus = BatStatus.NONE;
 19 
 20         private Process curProcess = new Process();
 21 
 22         public MainForm()
 23         {
 24             InitializeComponent();
 25         }
 26 
 27         private void MainForm_Load(object sender, EventArgs e)
 28         {
 29             InitInfo();
 30         }
 31 
 32         private void InitInfo()
 33         {
 34             curProcess.OutputDataReceived -= new DataReceivedEventHandler(ProcessOutDataReceived);
 35             ProcessStartInfo p = new ProcessStartInfo();
 36             p.FileName = "cmd.exe";
 37             //p.Arguments = " -t 192.168.1.103";
 38             p.UseShellExecute = false;
 39             p.WindowStyle = ProcessWindowStyle.Hidden;
 40             p.CreateNoWindow = true;
 41             p.RedirectStandardError = true;
 42             p.RedirectStandardInput = true;
 43             p.RedirectStandardOutput = true;
 44             curProcess.StartInfo = p;
 45             curProcess.Start();
 46 
 47             curProcess.BeginOutputReadLine();
 48             curProcess.OutputDataReceived += new DataReceivedEventHandler(ProcessOutDataReceived);
 49         }
 50 
 51         /// <summary>
 52         /// 开始命令行
 53         /// </summary>
 54         /// <param name="sender"></param>
 55         /// <param name="e"></param>
 56         private void btnStart_Click(object sender, EventArgs e)
 57         {
 58             if (string.IsNullOrEmpty(this.txtCommand.Text.Trim()))
 59             {
 60                 MessageBox.Show("请输入命令");
 61             }
 62             if (curBatSataus != BatStatus.ON)
 63             {
 64                 curProcess.StandardInput.WriteLine(this.txtCommand.Text.Trim());
 65                 curBatSataus = BatStatus.ON;
 66             }
 67             else {
 68                 MessageBox.Show("当前进程正在运行,请先关闭");
 69             }
 70 
 71         }
 72 
 73         /// <summary>
 74         /// 结束命令行
 75         /// </summary>
 76         /// <param name="sender"></param>
 77         /// <param name="e"></param>
 78         private void btnStop_Click(object sender, EventArgs e)
 79         {
 80             if (curBatSataus == BatStatus.ON)
 81             {
 82                 curProcess.CancelOutputRead();//取消异步操作
 83                 curProcess.Kill();
 84                 curBatSataus = BatStatus.OFF;
 85                 //如果需要手动关闭,则关闭后再进行初始化
 86                 InitInfo();
 87             }
 88         }
 89 
 90         /// <summary>
 91         /// 进程接受事件
 92         /// </summary>
 93         /// <param name="sender"></param>
 94         /// <param name="e"></param>
 95         public void ProcessOutDataReceived(object sender, DataReceivedEventArgs e)
 96         {
 97             if (this.txtOutPutInfo.InvokeRequired)
 98             {
 99                 this.txtOutPutInfo.Invoke(new Action(() =>
100                 {
101                     this.txtOutPutInfo.AppendText(e.Data + "\r\n");
102                 }));
103             }
104             else {
105                 this.txtOutPutInfo.AppendText(e.Data + "\r\n");
106             }
107         }
108 
109         private void timer1_Tick(object sender, EventArgs e)
110         {
111             if ((string.IsNullOrEmpty(this.curProcess.StartInfo.FileName) || this.curProcess.StandardInput.BaseStream.CanWrite) && curBatSataus != BatStatus.OFF)
112             {
113                 curBatSataus = BatStatus.OFF;
114 
115             }
116         }
117 
118     }
119 
120     /// <summary>
121     /// 命令状态
122     /// </summary>
123     public enum BatStatus {
124         NONE = 0,
125         ON = 1,
126         OFF = 2
127     }
128 }
复制代码
复制代码

备注:

关于如何在命令行执行过程中【如:Ping 192.168.1.100 -t】,键入快捷键【如:Ctrl+C】等操作,目前还没有实现。目前采用的就强制关闭进程方法

源码下载

 

 

出处:https://www.cnblogs.com/hsiang/p/6596276.html

posted on   jack_Meng  阅读(1301)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2020-12-17 使用命名管道承载gRPC,以及适用场景
2020-12-17 Protobuf3语法详解
2020-12-17 打造跨平台.NET Core后台服务
2016-12-17 C# Bitmap类型与Byte[]类型相互转化
2014-12-17 用命令行实现“一键休眠”
2013-12-17 变量延迟详解,什么情况下该使用变量延迟?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示

喜欢请打赏

扫描二维码打赏

支付宝打赏

主题色彩