C# 动态输出Dos命令执行结果
发布时间:2020-12-16 01:13:57 所属栏目:百科 来源:网络整理
导读:本文以一个简单的小例子讲解如何将命令行信息实时的输出到文本框中。仅供学习分享使用,如有不足之处,还请指正。 概述 在C#程序开发过程中,有时需要运行其它的程序并获得输出的结果来进行进一步的处理。一般第三方的程序,主要通过进程来调用,如果能够获
本文以一个简单的小例子讲解如何将命令行信息实时的输出到文本框中。仅供学习分享使用,如有不足之处,还请指正。 概述 在C#程序开发过程中,有时需要运行其它的程序并获得输出的结果来进行进一步的处理。一般第三方的程序,主要通过进程来调用,如果能够获取第三方程序执行过程中的信息,就显得方便而有用。 涉及知识点:
效果图 如下【如果命令执行完毕,会自动结束,如果中断进程,可以手动点击结束进程】: 核心代码 主要代码如下: 1 using System; 2 System.Collections.Generic; 3 System.ComponentModel; 4 System.Data; 5 System.Diagnostics; 6 System.Drawing; 7 System.Linq; 8 System.Runtime.InteropServices; 9 System.Text; 10 System.Threading; 11 System.Threading.Tasks; 12 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 void InitInfo() 33 34 curProcess.OutputDataReceived -= DataReceivedEventHandler(ProcessOutDataReceived); 35 ProcessStartInfo p = 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 = 42 p.RedirectStandardInput = 43 p.RedirectStandardOutput = 44 curProcess.StartInfo = p; 45 curProcess.Start(); 46 47 curProcess.BeginOutputReadLine(); 48 curProcess.OutputDataReceived += 49 50 51 /// <summary> 52 /// 开始命令行 53 </summary> 54 <param name="sender"></param> 55 <param name="e"></param> 56 void btnStart_Click( 57 58 if (string.IsNullOrEmpty(this.txtCommand.Text.Trim())) 59 { 60 MessageBox.Show(请输入命令); 61 } 62 if (curBatSataus != BatStatus.ON) 63 64 curProcess.StandardInput.WriteLine(.txtCommand.Text.Trim()); 65 curBatSataus = BatStatus.ON; 66 67 else { 68 MessageBox.Show(当前进程正在运行,请先关闭 69 70 71 72 73 74 结束命令行 75 76 77 78 void btnStop_Click( 79 80 if (curBatSataus == 81 82 curProcess.CancelOutputRead();取消异步操作 83 curProcess.Kill(); 84 curBatSataus = BatStatus.OFF; 85 如果需要手动关闭,则关闭后再进行初始化 86 InitInfo(); 87 88 89 90 91 进程接受事件 92 93 94 95 void ProcessOutDataReceived( 96 97 .txtOutPutInfo.InvokeRequired) 98 99 this.txtOutPutInfo.Invoke(new Action(() => 100 { 101 this.txtOutPutInfo.AppendText(e.Data + rn102 })); 103 104 105 106 107 108 109 void timer1_Tick(110 111 if ((this.curProcess.StartInfo.FileName) || this.curProcess.StandardInput.BaseStream.CanWrite) && curBatSataus != BatStatus.OFF) 112 113 curBatSataus =114 115 116 117 118 } 119 120 121 命令状态 122 123 enum BatStatus { 124 NONE = 0,125 ON = 1126 OFF = 2 127 128 } 备注: 关于如何在命令行执行过程中【如:Ping 192.168.1.100 -t】,键入快捷键【如:Ctrl+C】等操作,目前还没有实现。目前采用的就强制关闭进程方法 源码下载 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |