c# 管理员权限启动外部程序

发布于 2022-09-04 15:00:10 字数 2139 浏览 33 评论 0

1.目前程序启动的时候已经有管理员权限的判断了。但是启动外部程序的时候仍然提示需要提升权限
配置文件app.manifest也改过了`

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />`

2.启动权限为管理员

        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        //Application.SetCompatibleTextRenderingDefault(false);

        /**
         * 当前用户是管理员的时候,直接启动应用程序
         * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
         */
        //获得当前登录的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))
        {
            //如果是管理员,则直接运行
            App app = new App();
            app.Run(new Login());
        }
        else
        {
            //创建启动对象
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.UseShellExecute = true;
            startInfo.WorkingDirectory = Environment.CurrentDirectory;
            startInfo.FileName = Application.ExecutablePath;
            //设置启动动作,确保以管理员身份运行
            startInfo.Verb = "runas";
            try
            {
                System.Diagnostics.Process.Start(startInfo);
            }
            catch
            {
                return;
            }
            //退出
            Application.Exit();`

3.`启动程序代码

                p.StartInfo.FileName = startPath;
                p.StartInfo.Arguments = "1" ;//启动参数
                p.StartInfo.Verb = "runas";
                p.StartInfo.CreateNoWindow = true; //设置置不显示示窗口
                p.StartInfo.UseShellExecute = false;//不使用操作系统外壳程序启动进程
                p.StartInfo.ErrorDialog = false;
                p.Start();`

4.异常信息
图片描述

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文