效果图:
具体实现在代码中有详细的注释,请看代码。
实现执行CMD命令的核心代码(Cmd.cs):
[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Management;
using System.Globalization;
namespace Zbsoft.ExtendFunction
{
public class Cmd
{
/// <summary>
/// 是否终止调用CMD命令执行
/// </summary>
private static bool invokeCmdKilled = true;
/// <summary>
/// 获取或设置是否终止调用CMD命令执行
/// </summary>
public static bool InvokeCmdKilled
{
get { return invokeCmdKilled; }
set
{
invokeCmdKilled = value;
if (invokeCmdKilled)
{
if (p != null && !p.HasExited)
{
killProcess(p.Id);
}
}
}
}
private static Process p;
private static Action<string> RefreshResult;
/// <summary>
/// 调用CMD命令,执行指定的命令,并返回命令执行返回结果字符串
/// </summary>
/// <param name="cmdArgs">命令行</param>
/// <param name="RefreshResult">刷新返回结果字符串的事件</param>
/// <returns></returns>
public static void InvokeCmd(string cmdArgs, Action<string> pRefreshResult = null)
{
InvokeCmdKilled = false;
RefreshResult = pRefreshResult;
if (p != null)
{
p.Close();
p = null;
}
p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.ErrorDataReceived += new DataReceivedEventHandler(p_ErrorDataReceived);
p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.BeginErrorReadLine();
p.BeginOutputReadLine();
string[] cmds = cmdArgs.Split(new char[] { ‘\r‘, ‘\n‘ }, StringSplitOptions.RemoveEmptyEntries);
foreach (var v in cmds)
{
Thread.Sleep(200);
p.StandardInput.WriteLine(v);
}
//p.StandardInput.WriteLine("exit");
p.WaitForExit();
p.Dispose();
p.Close();
p = null;
InvokeCmdKilled = true;
}
/// <summary>
/// 输入交互式命令
/// </summary>
/// <param name="cmd"></param>
public static void InputCmdLine(string cmd)
{
if (p == null) return;
string[] cmds = cmd.Split(new char[] { ‘\r‘, ‘\n‘ }, StringSplitOptions.RemoveEmptyEntries);
foreach (var v in cmds)
{
Thread.Sleep(200);
p.StandardInput.WriteLine(v);
}
}
/// <summary>
/// 异步读取标准输出信息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
static void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (RefreshResult != null && e.Data != null)
RefreshResult(e.Data + "\r\n");
}
/// <summary>
/// 异步读取错误消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
static void p_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
if (RefreshResult != null && e.Data != null)
{
RefreshResult(e.Data + "\r\n");
}
}
/// <summary>
/// 关闭指定进程ID的进程以及子进程(关闭进程树)
/// </summary>
/// <param name="id"></param>
public static void FindAndKillProcess(int id)
{
killProcess(id);
}
/// <summary>
/// 关闭指定进程名称的进程以及子进程(关闭进程树)
/// </summary>
/// <param name="name"></param>
public static void FindAndKillProcess(string name)
{
foreach (Process clsProcess in Process.GetProcesses())
{
if ((clsProcess.ProcessName.StartsWith(name, StringComparison.CurrentCulture)) || (clsProcess.MainWindowTitle.StartsWith(name, StringComparison.CurrentCulture)))
killProcess(clsProcess.Id);
}
}
/// <summary>
/// 关闭进程树
/// </summary>
/// <param name="pid"></param>
/// <returns></returns>
private static bool killProcess(int pid)
{
Process[] procs = Process.GetProcesses();
for (int i = 0; i < procs.Length; i++)
{
if (getParentProcess(procs[i].Id) == pid)
killProcess(procs[i].Id);
}
try
{
Process myProc = Process.GetProcessById(pid);
myProc.Kill();
}
//进程已经退出
catch (ArgumentException)
{
;
}
return true;
}
/// <summary>
/// 获取父进程ID
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
private static int getParentProcess(int Id)
{
int parentPid = 0;
using (ManagementObject mo = new ManagementObject("win32_process.handle=‘" + Id.ToString(CultureInfo.InvariantCulture) + "‘"))
{
try
{
mo.Get();
}
catch (ManagementException)
{
return -1;
}
parentPid = Convert.ToInt32(mo["ParentProcessId"], CultureInfo.InvariantCulture);
}
return parentPid;
}
}
}
调用上述核心类的窗口代码(Form2.cs):
[csharp]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace Zbsoft.Test
{
public partial class Form2 : Form
{
Thread cmdThread;
private Action<string> rf;
public Form2()
{
InitializeComponent();
}
/// <summary>
/// 按CTRL+Enter键开始执行命令
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void textBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Enter && e.Control)
{
if (this.button3.Enabled)
this.button3_Click(null, null);
else
this.button4_Click(null, null);
}
}
private void Form2_Load(object sender, EventArgs e)
{
this.textBox1.Text = "help\r\ndir\r\nping 127.0.0.1";
rf = this.refreshCmdTxt;
this.richTextBox1.AppendText("Dos命令执行程序,支持批命令执行。按Ctrl+Enter键开始执行。如果一个命令长时间不能结束的,如ping 127.0.0.1 -t,“停止执行”按钮可强制终止执行。\r\n");
this.richTextBox1.AppendText("\r\n你的网卡Mac地址:" + Zbsoft.ExtendFunction.HardwareInfo.getID_NetCardId());
this.richTextBox1.AppendText(",Cpu序列号:" + Zbsoft.ExtendFunction.HardwareInfo.getID_CpuId());
this.richTextBox1.AppendText(",硬盘序列号:" + Zbsoft.ExtendFunction.HardwareInfo.getID_HardDiskId() + "\r\n");
this.richTextBox1.AppendText("\r\n常用的命令:\r\n");
this.richTextBox1.AppendText(@" ASSOC 显示或修改文件扩展名关联。
ATTRIB 显示或更改文件属性。
BREAK 设置或清除扩展式 CTRL+C 检查。
BCDEDIT 设置启动数据库中的属性以控制启动加载。
CACLS 显示或修改文件的访问控制列表(ACL)。
CALL 从另一个批处理程序调用这一个。
CD 显示当前目录的名称或将其更改。
CHCP 显示或设置活动代码页数。
CHDIR 显示当前目录的名称或将其更改。
CHKDSK 检查磁盘并显示状态报告。
CHKNTFS 显示或修改启动时间磁盘检查。
CLS 清除屏幕。
CMD 打开另一个 Windows 命令解释程序窗口。
COLOR 设置默认控制台前景和背景颜色。
COMP 比较两个或两套文件的内容。
COMPACT 显示或更改 NTFS 分区上文件的压缩。
CONVERT 将 FAT 卷转换成 NTFS。您不能转换当前驱动器。
COPY 将至少一个文件复制到另一个位置。
DATE 显示或设置日期。
DEL 删除至少一个文件。
DIR 显示一个目录中的文件和子目录。
DISKCOMP 比较两个软盘的内容。
DISKCOPY 将一个软盘的内容复制到另一个软盘。
DISKPART 显示或配置磁盘分区属性。
DOSKEY 编辑命令行、调用 Windows 命令并创建宏。
DRIVERQUERY 显示当前设备驱动程序状态和属性。
ECHO 显示消息,或将命令回显打开或关上。
ENDLOCAL 结束批文件中环境更改的本地化。
ERASE 删除一个或多个文件。
EXIT 退出 CMD.EXE 程序(命令解释程序)。
FC 比较两个文件或两个文件集并显示它们之间的不同。
FIND 在一个或多个文件中搜索一个文本字符串。
FINDSTR 在多个文件中搜索字符串。
FOR 为一套文件中的每个文件运行一个指定的命令。
FORMAT 格式化磁盘,以便跟 Windows 使用。
FSUTIL 显示或配置文件系统的属性。
FTYPE 显示或修改用在文件扩展名关联的文件类型。
GOTO 将 Windows 命令解释程序指向批处理程序中某个带标签的行。
GPRESULT 显示机器或用户的组策略信息。
GRAFTABL 启用 Windows 在图形模式显示扩展字符集。
HELP 提供 Windows 命令的帮助信息。
ICACLS 显示、修改、备份或还原文件和目录的 ACL。
IF 在批处理程序中执行有条件的处理过程。
IPCONFIG 网络配置
LABEL 创建、更改或删除磁盘的卷标。
MD 创建一个目录。
MKDIR 创建一个目录。
MKLINK 创建符号链接和硬链接
MODE 配置系统设备。
MORE 逐屏显示输出。
MOVE 将一个或多个文件从一个目录移动到另一个目录。
NET 这个命令太强大了,net help自己看看吧
NETSTAT 网络状态
OPENFILES 显示远程用户为了文件共享而打开的文件。
PATH 为可执行文件显示或设置搜索路径。
PAUSE 停止批处理文件的处理并显示信息。
PING 检测网络是否通畅
POPD 还原由 PUSHD 保存的当前目录上一次的值。
PRINT 打印一个文本文件。
PROMPT 改变 Windows 命令提示。
PUSHD 保存当前目录,然后对其进行更改。
RD 删除目录。
RECOVER 从损坏的磁盘中恢复可读取的信息。
REM 记录批处理文件或 CONFIG.SYS 中的注释。
REN 重新命名文件。
RENAME 重新命名文件。
REPLACE 替换文件。
RMDIR 删除目录。
ROBOCOPY 复制文件和目录树的高级实用程序
ROUTE 路由命令
SET 显示、设置或删除 Windows 环境变量。
SETLOCAL 开始用批文件改变环境的本地化。
SC 显示或配置服务(后台处理)。
SCHTASKS 安排命令和程序在一部计算机上按计划运行。
SHIFT 调整批处理文件中可替换参数的位置。
SHUTDOWN 让机器在本地或远程正确关闭。
SORT 将输入排序。
START 打开单独视窗运行指定程序或命令。
SUBST 将驱动器号与路径关联。
SYSTEMINFO 显示机器的具体的属性和配置。
TASKLIST 显示包括服务的所有当前运行的任务。
TASKKILL 终止正在运行的进程或应用程序。
TIME 显示或设置系统时间。
TITLE 设置 CMD.EXE 会话的窗口标题。
TRACERT 用于将数据包从计算机传递到目标位置的一组IP路由器,以及每个跃点所需的时间。
TREE 以图形显示启动器或路径的目录结构。
TYPE 显示文本文件的内容。
VER 显示 Windows 的版本。
VERIFY 告诉 Windows 验证文件是否正确写入磁盘。
VOL 显示磁盘卷标和序列号。
XCOPY 复制文件和目录树。
WMIC 在交互命令外壳里显示 WMI 信息。");
}
private void StartCmd()
{
Zbsoft.ExtendFunction.Cmd.InvokeCmd(this.textBox1.Text, this.refreshCmdTxt);
}
/// <summary>
/// 显示返回结果
/// </summary>
/// <param name="txt"></param>
private void refreshCmdTxt(string txt)
{
if (!this.Visible) return;
if (this.richTextBox1.InvokeRequired)
{
try
{
this.richTextBox1.Invoke(this.rf, txt);
}
catch { }
}
else
{
this.richTextBox1.AppendText(txt);
this.richTextBox1.ScrollToCaret();
}
}
/// <summary>
/// 停止执行
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
Zbsoft.ExtendFunction.Cmd.InvokeCmdKilled = true;
this.button3.Enabled = true;
}
/// <summary>
/// 清空返回结果
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
this.richTextBox1.Clear();
}
/// <summary>
/// 开始执行命令
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
if (cmdThread != null && !Zbsoft.ExtendFunction.Cmd.InvokeCmdKilled)
{
MessageBox.Show("程序正在执行中,请稍候或中止后再执行!");
return;
}
if (string.IsNullOrEmpty(this.textBox1.Text)) return;
if (cmdThread != null)
{
cmdThread.Abort();
cmdThread = null;
}
cmdThread = new Thread(StartCmd);
cmdThread.Start();
this.button3.Enabled = false;
}
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
if (cmdThread != null)
{
cmdThread.Abort();
cmdThread = null;
}
}
/// <summary>
/// 输入交互式命令
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
if (cmdThread == null)
return;
Zbsoft.ExtendFunction.Cmd.InputCmdLine(this.textBox1.Text);
}
/// <summary>
/// 输入退出命令
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button5_Click(object sender, EventArgs e)
{
if (cmdThread == null)
return;
Zbsoft.ExtendFunction.Cmd.InputCmdLine("exit");
this.button3.Enabled = true;
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
Zbsoft.ExtendFunction.Cmd.InvokeCmdKilled = true;
}
}
}
窗口文件:Form2.Designer.cs
[csharp] view plaincopy
namespace Zbsoft.Test
{
partial class Form2
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.textBox1 = new System.Windows.Forms.TextBox();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.label1 = new System.Windows.Forms.Label();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.button3 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button1 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.button5 = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.AutoCompleteCustomSource.AddRange(new string[] {
"ASSOC",
"ATTRIB",
"BREAK",
"BCDEDIT",
"CACLS",
"CALL",
"CD",
"CHCP",
"CHDIR",
"CHKDSK",
"CHKNTFS",
"CLS",
"CMD",
"COLOR",
"COMP",
"COMPACT",
"CONVERT",
"COPY",
"DATE",
"DEL",
"DIR",
"DISKCOMP",
"DISKCOPY",
"DISKPART",
"DOSKEY",
"DRIVERQUERY",
"ECHO",
"ENDLOCAL",
"ERASE",
"EXIT",
"FC",
"FIND",
"FINDSTR",
"FOR",
"FORMAT",
"FSUTIL",
"FTYPE",
"GOTO",
"GPRESULT",
"GRAFTABL",
"HELP",
"ICACLS",
"IF",
"LABEL",
"MD",
"MKDIR",
"MKLINK",
"MODE",
"MORE",
"MOVE",
"OPENFILES",
"PATH",
"PAUSE",
"POPD",
"PRINT",
"PROMPT",
"PUSHD",
"RD",
"RECOVER",
"REM",
"REN",
"RENAME",
"REPLACE",
"RMDIR",
"ROBOCOPY",
"SET",
"SETLOCAL",
"SC",
"SCHTASKS",
"SHIFT",
"SHUTDOWN",
"SORT",
"START",
"SUBST",
"SYSTEMINFO",
"TASKLIST",
"TASKKILL",
"TIME",
"TITLE",
"TREE",
"TYPE",
"VER",
"VERIFY",
"VOL",
"XCOPY",
"WMIC"});
this.textBox1.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Append;
this.textBox1.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource;
this.textBox1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.textBox1.Location = new System.Drawing.Point(5, 38);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.textBox1.Size = new System.Drawing.Size(838, 53);
this.textBox1.TabIndex = 0;
this.textBox1.Text = "ping 10.84.184.1 -t";
this.textBox1.PreviewKeyDown += new System.Windows.Forms.PreviewKeyDownEventHandler(this.textBox1_PreviewKeyDown);
//
// richTextBox1
//
this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.richTextBox1.Location = new System.Drawing.Point(5, 5);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(838, 289);
this.richTextBox1.TabIndex = 1;
this.richTextBox1.Text = "";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(7, 14);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(173, 12);
this.label1.TabIndex = 2;
this.label1.Text = "请输入待执行的命令,回车执行";
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
this.splitContainer1.Location = new System.Drawing.Point(0, 0);
this.splitContainer1.Name = "splitContainer1";
this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.button5);
this.splitContainer1.Panel1.Controls.Add(this.button4);
this.splitContainer1.Panel1.Controls.Add(this.button3);
this.splitContainer1.Panel1.Controls.Add(this.button2);
this.splitContainer1.Panel1.Controls.Add(this.button1);
this.splitContainer1.Panel1.Controls.Add(this.textBox1);
this.splitContainer1.Panel1.Controls.Add(this.label1);
this.splitContainer1.Panel1.Padding = new System.Windows.Forms.Padding(5, 0, 5, 5);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.richTextBox1);
this.splitContainer1.Panel2.Padding = new System.Windows.Forms.Padding(5);
this.splitContainer1.Size = new System.Drawing.Size(848, 399);
this.splitContainer1.SplitterDistance = 96;
this.splitContainer1.TabIndex = 3;
//
// button3
//
this.button3.Location = new System.Drawing.Point(231, 9);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(75, 23);
this.button3.TabIndex = 5;
this.button3.Text = "开始执行";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(605, 9);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(95, 23);
this.button2.TabIndex = 4;
this.button2.Text = "清空返回结果";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// button1
//
this.button1.Location = new System.Drawing.Point(511, 9);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 3;
this.button1.Text = "停止执行";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button4
//
this.button4.Location = new System.Drawing.Point(320, 9);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(75, 23);
this.button4.TabIndex = 6;
this.button4.Text = "交互输入";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.button4_Click);
//
// button5
//
this.button5.Location = new System.Drawing.Point(405, 9);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(94, 23);
this.button5.TabIndex = 7;
this.button5.Text = "输入退出命令";
this.button5.UseVisualStyleBackColor = true;
this.button5.Click += new System.EventHandler(this.button5_Click);
//
// Form2
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(848, 399);
this.Controls.Add(this.splitContainer1);
this.Name = "Form2";
this.Text = "Dos Command";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form2_FormClosing);
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Form2_FormClosed);
this.Load += new System.EventHandler(this.Form2_Load);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel1.PerformLayout();
this.splitContainer1.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
this.splitContainer1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button5;
private System.Windows.Forms.Button button4;
}
}