C#启动外部程序的几种方法

一、四种方法

启动外部程序不等待其退出;

启动外部程序等待其推出;

启动外部程序无限等待其退出;

启动外部程序通过事件监视其退出。

二、通过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);

        }

注:以上包含了以管理员权限运行外部程序的方法

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值