应用程序中经常会在终端窗口(Terminal Window,以前称为 DOS 窗口)调用运行指定参数的其他应用程序。
这里给出静默式执行程序的实例代码。
using System;
using System.Data;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
namespace Legalsoft.Truffer.Lab
{
public partial class Form1 : Form
{
private void button1_Click(object sender, EventArgs e)
{
Execute("net user zero baidu.com /add", 0);
}
public static string Execute(string dosCommand, int outtime)
{
string output = "";
if (dosCommand != null && dosCommand != "")
{
//创建进程对象
Process process = new Process();
//创建进程时使用的一组值,如下面的属性
ProcessStartInfo startinfo = new ProcessStartInfo();
//设定需要执行的命令程序
//以下是隐藏cmd窗口的方法
startinfo.FileName = "cmd.exe";
//设定参数,要输入到命令程序的字符,其中"/c"表示执行完命令后马上退出
startinfo.Arguments = "/c" + dosCommand;
//不使用系统外壳程序启动
startinfo.UseShellExecute = false;
//不重定向输入
startinfo.RedirectStandardInput = false;
//重定向输出,而不是默认的显示在dos控制台上
startinfo.RedirectStandardOutput = true;
//不创建窗口
startinfo.CreateNoWindow = true;
process.StartInfo = startinfo;
try
{
//开始进程
if (process.Start())
{
if (outtime == 0)
{
process.WaitForExit();
}
else
{
process.WaitForExit(outtime);
}
//读取进程的输出
output = process.StandardOutput.ReadToEnd();
}
}
catch
{
}
finally
{
if (process != null)
{
process.Close();
}
}
}
return output;
}
}
}