Program.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using System.Windows.Forms;
  6. namespace RevokeMsgPatcher
  7. {
  8. static class Program
  9. {
  10. /// <summary>
  11. /// 应用程序的主入口点。
  12. /// </summary>
  13. [STAThread]
  14. static void Main()
  15. {
  16. #if DEBUG
  17. Application.EnableVisualStyles();
  18. Application.SetCompatibleTextRenderingDefault(false);
  19. Application.Run(new FormMain());
  20. #else
  21. try
  22. {
  23. Application.EnableVisualStyles();
  24. Application.SetCompatibleTextRenderingDefault(false);
  25. //当前用户是管理员的时候,直接启动应用程序
  26. //如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
  27. //获得当前登录的Windows用户标示
  28. System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
  29. System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
  30. //判断当前登录用户是否为管理员
  31. if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
  32. {
  33. //如果是管理员,则直接运行
  34. Application.Run(new FormMain());
  35. }
  36. else
  37. {
  38. //创建启动对象
  39. System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
  40. startInfo.UseShellExecute = true;
  41. startInfo.WorkingDirectory = Environment.CurrentDirectory;
  42. startInfo.FileName = Application.ExecutablePath;
  43. //设置启动动作,确保以管理员身份运行
  44. startInfo.Verb = "runas";
  45. try
  46. {
  47. System.Diagnostics.Process.Start(startInfo);
  48. }
  49. catch
  50. {
  51. return;
  52. }
  53. //退出
  54. Application.Exit();
  55. }
  56. }
  57. catch (Exception ex)
  58. {
  59. MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
  60. }
  61. #endif
  62. }
  63. static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
  64. {
  65. MessageBox.Show(e.Exception.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
  66. }
  67. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  68. {
  69. MessageBox.Show((e.ExceptionObject as Exception).Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
  70. }
  71. }
  72. }