Program.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Security.Principal;
  5. using System.Text;
  6. using System.Windows.Forms;
  7. namespace UAS_BARCODEIO
  8. {
  9. static class Program
  10. {
  11. /// <summary>
  12. /// 应用程序的主入口点。
  13. /// </summary>
  14. [STAThread]
  15. static void Main()
  16. {
  17. WindowsIdentity identity = WindowsIdentity.GetCurrent();
  18. WindowsPrincipal principal = new WindowsPrincipal(identity);
  19. Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
  20. //处理UI线程异常
  21. Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
  22. //处理非UI线程异常
  23. AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
  24. Application.EnableVisualStyles();
  25. Application.SetCompatibleTextRenderingDefault(false);
  26. //如果是管理员的身份
  27. if (principal.IsInRole(WindowsBuiltInRole.Administrator))
  28. {
  29. Application.Run(new 极测_出货清单打印());
  30. }
  31. else
  32. {
  33. //创建启动对象
  34. System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
  35. // 设置运行文件
  36. startInfo.FileName = Application.ExecutablePath;
  37. //设置启动动作,确保以管理员身份运行
  38. startInfo.Verb = "runas";
  39. //如果不是管理员,则启动UAC
  40. System.Diagnostics.Process.Start(startInfo);
  41. //退出 System.Windows.Forms.Application.Exit();
  42. }
  43. }
  44. static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
  45. {
  46. string str = GetExceptionMsg(e.Exception, e.ToString());
  47. MessageBox.Show(str, "操作异常", MessageBoxButtons.OK, MessageBoxIcon.Stop);
  48. }
  49. //未处理的异常统一通过这里返回
  50. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  51. {
  52. string str = GetExceptionMsg(e.ExceptionObject as Exception, e.ToString());
  53. MessageBox.Show(str, "操作异常", MessageBoxButtons.OK, MessageBoxIcon.Stop);
  54. }
  55. /// <summary>
  56. /// 生成自定义异常消息
  57. /// </summary>
  58. /// <param name="ex">异常对象</param>
  59. /// <param name="backStr">备用异常消息:当ex为null时有效</param>
  60. /// <returns>异常字符串文本</returns>
  61. static string GetExceptionMsg(Exception ex, string backStr)
  62. {
  63. StringBuilder sb = new StringBuilder();
  64. if (ex != null)
  65. {
  66. sb.AppendLine(ex.Message);
  67. //sb.AppendLine(ex.StackTrace);
  68. //sb.AppendLine("【异常方法】:" + ex.TargetSite);
  69. }
  70. return sb.ToString();
  71. }
  72. }
  73. }