本文实现了C#隐式运行CMD命令的功能。下图是实例程序的主画面。在命令文本框输入DOS命令,点击“Run”按钮,在下面的文本框中输出运行结果。
下面是程序的完整代码。本程序没有使用p.StandardOutput.ReadtoEnd()和p.StandardOutput.ReadLine()方法来获得输出,因为这些方法执行后画面容易卡死。而是通过调用异步方法BeginOutputReadLine来获取输出,并在事件p.OutputDataReceived的事件处理方法中来处理结果。
using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
namespace RunDosCommandForm
{
publicpartialclassForm1 : Form
{
publicForm1()
{
InitializeComponent();
}
privatevoidbutton1_Click(object sender, EventArgse)
{
ExcuteDosCommand(textBox1.Text);
}
privatevoidExcuteDosCommand(string cmd)
{
try
{
Process p = newProcess();
p.StartInfo.FileName = "cmd&