使用管理员权限重新运行程序

      // 检查是否是管理员身份   
        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());
                }

            }

        }

 

posted @ 2014-10-13 17:42  b̶i̶n̶g̶.̶  阅读(570)  评论(0编辑  收藏  举报