程序发布后,必须以管理员身份登陆

    项目中打包程序,在后续更新时需要管理员身份运行,固将程序运行时,使用管理员运行。

作如下设置

1)在App.cs中增加以下代码:

复制代码
        /// 
        /// 检查是否是管理员身份
        /// 
        private void CheckAdministrator()
        {
            var wi = WindowsIdentity.GetCurrent();
            var wp = new WindowsPrincipal(wi);

            bool runAsAdmin = wp.IsInRole(WindowsBuiltInRole.Administrator);

            if (!runAsAdmin)
            {
                // It is not possible to launch a ClickOnce app as administrator directly,
                // so instead we launch the app as administrator in a new process.
                var processInfo = new ProcessStartInfo(Assembly.GetExecutingAssembly().CodeBase);

                // The following properties run the new process as administrator
                processInfo.UseShellExecute = true;
                processInfo.Verb = "runas";

                // Start the new process
                try
                {
                    Process.Start(processInfo);
                }
                catch (Exception ex)
                {
                    ex.WriteLog();
                }

                // Shut down the current process
                Environment.Exit(0);
            }
        }
复制代码

2)重写 OnStartup 函数 

复制代码
protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            CheckAdministrator();
//如果不是管理员,程序会直接退出。
StartupUri = new Uri("MainWindow.xaml", UriKind.RelativeOrAbsolute); }
复制代码

转载于:https://www.cnblogs.com/hanjiaxu/p/4682283.html

你可能感兴趣的:(程序发布后,必须以管理员身份登陆)