使用管理员权限重新运行程序
- // 检查是否是管理员身份
- 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());
- }
- }
- }
版权声明:本文为gaobing原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。