1. // 检查是否是管理员身份
  2. private static bool CheckAdministrator()
  3. {
  4. WindowsIdentity wi = null;
  5. try
  6. {
  7. wi = WindowsIdentity.GetCurrent();
  8. if (wi == null) throw new Exception("未将对象仅用到对象的实例!");
  9. var wp = new WindowsPrincipal(wi);
  10. var runAsAdmin = wp.IsInRole(WindowsBuiltInRole.Administrator);
  11. if (runAsAdmin) return true;
  12. var processInfo = new ProcessStartInfo(Assembly.GetExecutingAssembly().CodeBase)
  13. {
  14. UseShellExecute = true,
  15. Verb = "runas"
  16. };
  17. Process.Start(processInfo);
  18. return false;
  19. }
  20. catch
  21. {
  22. Console.WriteLine("失败!");
  23. return true;
  24. }
  25. finally
  26. {
  27. if (wi != null)
  28. wi.Dispose();
  29. }
  30. }

 

 应用

  1. /// <summary>
  2. /// 应用程序的主入口点。
  3. /// </summary>
  4. [STAThread]
  5. static void Main()
  6. {
  7. if (CheckAdministrator())
  8. {
  9. int count = 0;
  10. Process[] myProcess = Process.GetProcesses();
  11. foreach (Process _Process in myProcess)
  12. {
  13. if (_Process.ProcessName == Process.GetCurrentProcess().ProcessName)
  14. {
  15. count++;
  16. }
  17. }
  18. if (count > 1)
  19. {
  20. MessageBox.Show("程序已启动,请勿重复打开!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  21. }
  22. else
  23. {
  24. Application.EnableVisualStyles();
  25. Application.SetCompatibleTextRenderingDefault(false);
  26. Application.Run(new MainForm());
  27. }
  28. }
  29. }

 

版权声明:本文为gaobing原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/gaobing/p/4022707.html