zoukankan      html  css  js  c++  java
  • 使用管理员权限重新运行程序

          // 检查是否是管理员身份   
            private static bool CheckAdministrator()
            {
                WindowsIdentity wi = null;
                try
                {
                    wi = WindowsIdentity.GetCurrent();
                    if (wi == null) throw new Exception("未将对象仅用到对象的实例!");
                    var wp = new WindowsPrincipal(wi);
                    var runAsAdmin = wp.IsInRole(WindowsBuiltInRole.Administrator);
                    if (runAsAdmin) return true;
                    var processInfo = new ProcessStartInfo(Assembly.GetExecutingAssembly().CodeBase)
                    {
                        UseShellExecute = true,
                        Verb = "runas"
                    };
    
                    Process.Start(processInfo);
                    return false;
                }
                catch
                {
                    Console.WriteLine("失败!");
                    return true;
                }
                finally
                {
                    if (wi != null)
                        wi.Dispose();
                }
            }

     应用

        /// <summary>
            /// 应用程序的主入口点。
            /// </summary>
            [STAThread]
            static void Main()
            {
                if (CheckAdministrator())
                {
                    int count = 0;
                    Process[] myProcess = Process.GetProcesses();
                    foreach (Process _Process in myProcess)
                    {
                        if (_Process.ProcessName == Process.GetCurrentProcess().ProcessName)
                        {
                            count++;
                        }
                    }
                    if (count > 1)
                    {
                        MessageBox.Show("程序已启动,请勿重复打开!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else
                    {
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        Application.Run(new MainForm());
                    }
    
                }
    
            }
  • 相关阅读:
    集合容器概述
    enum枚举类型
    this关键字、this()、super()
    重载与重写
    nginx报404的可能错误
    nginx常用命令
    vbs系统监控
    VBS windows监控
    Oracle SQL优化[转]
    shell /bin/bash^M: bad interpreter错误解决
  • 原文地址:https://www.cnblogs.com/gaobing/p/4022707.html
Copyright © 2011-2022 走看看