using MeterVision.Dlg; using MeterVision.Util; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Threading; namespace MeterVision { /// /// App.xaml 的交互逻辑 /// public partial class App : Application { // protected override void OnStartup(StartupEventArgs e) //{ // base.OnStartup(e); // this.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException); // // 设置许可证上下文为非商业用途 // //ExcelPackage.LicenseContext = LicenseContext.NonCommercial; //} private static Mutex mutex = new Mutex(true, "{E1805A91-1078-417D-9B65-43FCFCA504CC_ttpp}"); protected override void OnStartup(StartupEventArgs e) { //if (!mutex.WaitOne(TimeSpan.Zero, true)) //{ // //如果另一个实例已经拥有这个互斥锁,那么当前实列将不会继续运行 // MessageBox.Show("程序已经在运行。"); // Current.Shutdown(); // return; //} base.OnStartup(e); int instanceIndex = GetCurrentInstanceIndex(); //MessageBox.Show($"当前是第 {instanceIndex + 1} 个实例"); this.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException); MainWindow mainWindow = new MainWindow(); mainWindow.InstanceIndex = instanceIndex+1; this.MainWindow = mainWindow; LicenseMana.mLicenseModel = new LicenseModel() { IsPermanent = true }; mainWindow.Show(); // 检查是否已注册 //if (LicenseMana.IsLicensed()) //{ // // 已注册,显示主界面 // mainWindow.Show(); //} //else //{ // // 未注册,弹出注册对话框 // RegisterDlg registerDlg = new RegisterDlg(); // bool? result = registerDlg.ShowDialog(); // if (result == true) // { // // 用户成功注册,显示主界面 // mainWindow.Show(); // } // else // { // Shutdown(); // } //} //--------------------------------------------------------------------------------- } protected override void OnExit(ExitEventArgs e) { //释放互斥锁 //if(mutex != null) //{ // mutex.ReleaseMutex(); // mutex.Close(); //} base.OnExit(e); } private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { // 检查异常类型 if (e.Exception is AccessViolationException) { // 记录或处理访问违规错误 MessageBox.Show("访问无效内存,程序即将停止。", "错误", MessageBoxButton.OK, MessageBoxImage.Error); e.Handled = true; // 防止程序崩溃 } else { // 其他异常处理 MessageBox.Show($"发生错误: {e.Exception.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error); e.Handled = true; // 防止程序崩溃 } } private int GetCurrentInstanceIndex() { string processName = Process.GetCurrentProcess().ProcessName; var allProcesses = Process.GetProcessesByName(processName) .OrderBy(p => p.StartTime) // 按启动时间排序 .ToList(); int index = allProcesses.FindIndex(p => p.Id == Process.GetCurrentProcess().Id); return index; // 从0开始,表示第一个、第二个... } //////////////////////////////////////////////////////////////////////////////// } }