App.xaml.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using MeterVision.Dlg;
  2. using MeterVision.Util;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Configuration;
  6. using System.Data;
  7. using System.Linq;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using System.Windows;
  11. using System.Windows.Threading;
  12. namespace MeterVision
  13. {
  14. /// <summary>
  15. /// App.xaml 的交互逻辑
  16. /// </summary>
  17. public partial class App : Application
  18. {
  19. // protected override void OnStartup(StartupEventArgs e)
  20. //{
  21. // base.OnStartup(e);
  22. // this.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
  23. // // 设置许可证上下文为非商业用途
  24. // //ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
  25. //}
  26. private static Mutex mutex = new Mutex(true, "{E1805A91-1078-417D-9B65-43FCFCA504CC_tt}");
  27. protected override void OnStartup(StartupEventArgs e)
  28. {
  29. if (!mutex.WaitOne(TimeSpan.Zero, true))
  30. {
  31. //如果另一个实例已经拥有这个互斥锁,那么当前实列将不会继续运行
  32. MessageBox.Show("程序已经在运行。");
  33. Current.Shutdown();
  34. return;
  35. }
  36. base.OnStartup(e);
  37. this.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
  38. MainWindow mainWindow = new MainWindow();
  39. this.MainWindow = mainWindow;
  40. // 检查是否已注册
  41. if (LicenseMana.IsLicensed())
  42. {
  43. // 已注册,显示主界面
  44. mainWindow.Show();
  45. }
  46. else
  47. {
  48. // 未注册,弹出注册对话框
  49. RegisterDlg registerDlg = new RegisterDlg();
  50. bool? result = registerDlg.ShowDialog();
  51. if (result == true)
  52. {
  53. // 用户成功注册,显示主界面
  54. mainWindow.Show();
  55. }
  56. else
  57. {
  58. Shutdown();
  59. }
  60. }
  61. //---------------------------------------------------------------------------------
  62. }
  63. protected override void OnExit(ExitEventArgs e)
  64. {
  65. //释放互斥锁
  66. if(mutex != null)
  67. {
  68. mutex.ReleaseMutex();
  69. mutex.Close();
  70. }
  71. base.OnExit(e);
  72. }
  73. private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
  74. {
  75. // 检查异常类型
  76. if (e.Exception is AccessViolationException)
  77. {
  78. // 记录或处理访问违规错误
  79. MessageBox.Show("访问无效内存,程序即将停止。", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
  80. e.Handled = true; // 防止程序崩溃
  81. }
  82. else
  83. {
  84. // 其他异常处理
  85. MessageBox.Show($"发生错误: {e.Exception.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
  86. e.Handled = true; // 防止程序崩溃
  87. }
  88. }
  89. }
  90. }