1 /// <summary>
2 /// 判断程序是否是以管理员身份运行。
3 /// </summary>
4 public static bool IsRunAsAdmin()
5 {
6 WindowsIdentity id = WindowsIdentity.GetCurrent();
7 WindowsPrincipal principal = new WindowsPrincipal(id);
8 return principal.IsInRole(WindowsBuiltInRole.Administrator);
9 }
10 //不是以管理员身份开启,则自动以管理员身份重新打开程序
11 //写在构造里比较省资源
12 public LoginFrm()
13 {
14 try
15 {
16 //判断是否以管理员身份运行,不是则提示
17 if (!PublicUtil.IsRunAsAdmin())
18 {
19 ProcessStartInfo psi = new ProcessStartInfo();
20 psi.WorkingDirectory = Environment.CurrentDirectory;
21 psi.FileName = Application.ExecutablePath;
22 psi.UseShellExecute = true;
23 psi.Verb = "runas";
24 Process p = new Process();
25 p.StartInfo = psi;
26 p.Start();
27 Process.GetCurrentProcess().Kill();
28 }
29 }
30 catch (Exception ex)
31 {
32 ExceptionScheduler.ExceptionScheduler exceptionScheduler = new ExceptionScheduler.ExceptionScheduler(ex);
33 ShowMessageOnUI.ShowErrorMessage("程序无法获取Windows管理员身份运行,\n请手动使用Windows管理员身份运行");
34 }
35 InitializeComponent();
36 }