一、四种方法
启动外部程序不等待其退出;
启动外部程序等待其推出;
启动外部程序无限等待其退出;
启动外部程序通过事件监视其退出。
二、通过Process类启动外部程序的一般流程
1.创建Process对象
2.配置启动选项(输入输出等)
3.切换工作目录
4.设置外部程序名
5.设置传入参数
6.启动外部程序
7.等待程序结束
8.关闭程序
具体操作代码如下:
private void Button_Click(object sender, RoutedEventArgs e)
{
Process process = new Process();//创建process对象
process.StartInfo.UseShellExecute = false; //必要参数
process.StartInfo.RedirectStandardOutput = true;//输出参数设定
process.StartInfo.RedirectStandardInput = true;//传入参数设定
process.StartInfo.CreateNoWindow = true;
System.IO.Directory.SetCurrentDirectory("D:\\pro\\huaru\\Huaru\\ELTest\\WpfElApp\\bin\\Debug");
//设置工作目录为当前工作目录
process.StartInfo.FileName = "ndp48-x86-x64-allos-enu.exe";
//设置要打开的程序名
this.Close();
//process.Start(); //程序启动
//process.WaitForExit();//等待程序执行完退出进程
//MessageBox.Show("已完成安装");
//process.Close(); //关闭程序
//以管理员身份允许程序
//获得当前登录的Windows用户标示
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
//判断当前登录用户是否为管理员
if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
{
//如果是管理员,则直接运行
process.Start(); //程序启动
}
else
{
//创建启动对象
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = "ndp48-x86-x64-allos-enu.exe";
//设置启动动作,确保以管理员身份运行
startInfo.Verb = "runas";
try
{
System.Diagnostics.Process.Start(startInfo);
}
catch
{
MessageBox.Show("miss");
}
//退出
}
System.IO.Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
}
注:以上包含了以管理员权限运行外部程序的方法