Program.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using System.Windows.Forms;
  7. using System.Diagnostics;
  8. using HXX.Scanner.Common;
  9. namespace HXX.Scanner.Starter
  10. {
  11. static class Program
  12. {
  13. /// <summary>
  14. /// 应用程序的主入口点。
  15. /// </summary>
  16. [STAThread]
  17. static void Main(string[] Args)
  18. {
  19. /**
  20. * 当前用户是管理员的时候,直接启动应用程序
  21. * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
  22. */
  23. //获得当前登录的Windows用户标示
  24. System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
  25. //创建Windows用户主题
  26. Application.EnableVisualStyles();
  27. System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
  28. //判断当前登录用户是否为管理员
  29. if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
  30. {
  31. //如果是管理员,则直接运行
  32. Application.EnableVisualStyles();
  33. Application.SetCompatibleTextRenderingDefault(false);
  34. CustomExceptionHandlerForClient ExceptionHandler = new CustomExceptionHandlerForClient();
  35. Mutex mutex = new Mutex(true, "HXX_Scanner_ZX1", out bool CreatedNew);
  36. if (!CreatedNew)
  37. {
  38. MsgManager.Warn("程序已经启动!");
  39. }
  40. else
  41. {
  42. Process[] processes;
  43. processes = Process.GetProcessesByName("HXXScannerClient");
  44. if (processes.Length > 0)
  45. {
  46. MsgManager.Warn("程序已经启动!");
  47. }
  48. else
  49. {
  50. try
  51. {
  52. Application.Run(new frmStarter());
  53. mutex.ReleaseMutex();
  54. }
  55. catch (Exception ee)
  56. {
  57. mutex.ReleaseMutex();
  58. }
  59. }
  60. }
  61. }
  62. else
  63. {
  64. //创建启动对象
  65. System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
  66. //设置运行文件
  67. startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
  68. //设置启动参数
  69. startInfo.Arguments = String.Join(" ", Args);
  70. //设置启动动作,确保以管理员身份运行
  71. startInfo.Verb = "runas";
  72. //如果不是管理员,则启动UAC
  73. System.Diagnostics.Process.Start(startInfo);
  74. //退出
  75. System.Windows.Forms.Application.Exit();
  76. }
  77. }
  78. }
  79. }