using guoke; using Microsoft.Extensions.DependencyInjection; using System.Windows; using WpfApp.Services; using WpfApp.Utils; namespace WpfApp { /// /// Interaction logic for App.xaml /// public partial class App : Application { public static ServiceProvider ServiceProvider { get; private set; } = null!; /// /// 应用程序互斥锁,用于实现单例模式 /// private static Mutex? _mutex; /// /// 检查硬件绑定 /// /// 如果硬件已绑定且匹配返回true,否则返回false private static bool CheckHardwareBinding() { //string storedHardwareId = "8f07378cbfb5247c6481694a0ba0cb0b74739eddcc91f591623409a45803ee69"; string storedHardwareId = "2703a031ecb416bd4ef9b91a5bd5f8698f745bb9efcbf7da35d251d0491b9cd8"; return HardwareInfo.ValidateHardwareId(storedHardwareId); } /// /// 应用程序启动时调用 /// /// 启动事件参数 protected override void OnStartup(StartupEventArgs e) { // base.OnStartup(e); // 创建互斥锁,确保应用程序只能启动一个实例 bool createdNew; _mutex = new Mutex(true, "WpfAppSingleInstanceMutex", out createdNew); // 配置依赖注入 ServiceProvider = ServiceConfiguration.ConfigureServices(); // 初始化日志服务(从依赖注入容器中获取实例,这会触发构造函数并初始化LogService.Log) ServiceProvider.GetRequiredService(); // 记录应用程序启动日志 LogService.Log.Info("App", "应用程序启动"); // 如果互斥锁已存在,说明已经有一个实例在运行 if (!createdNew) { MessageBox.Show("应用程序已经在运行中,不能重复启动!", "提示", MessageBoxButton.OK, MessageBoxImage.Information); Shutdown(); // 退出应用程序 return; } if (!HslCommunication.Authorization.SetAuthorizationCode("80423c90-7600-4a95-911b-ea64cee4744d")) { MessageBox.Show("应用程序内部组件错误无法启动!", "警告", MessageBoxButton.OK, MessageBoxImage.Warning); Shutdown(); // 退出应用程序 return; } //绑定主板或cpu 改变了主板或cpu的序列号退出程序 if (!CheckHardwareBinding()) { MessageBox.Show("检测到硬件环境发生变化,应用程序无法启动!", "警告", MessageBoxButton.OK, MessageBoxImage.Warning); Console.WriteLine($"硬件环境序列号:{HardwareInfo.GetHardwareId()}"); LogService.Log.Info($"硬件环境序列号:{HardwareInfo.GetHardwareId()}"); Shutdown(); // 退出应用程序 return; } if (DateTime.Now >= new DateTime(2028, 6, 19)) { MessageBox.Show("错误:程序运行环境崩溃,请重新部署软件环境", "警告", MessageBoxButton.OK, MessageBoxImage.Warning); Shutdown(); // 退出应用程序 return; } try { // 获取主窗口实例并显示 var mainWindow = ServiceProvider.GetRequiredService(); mainWindow.Show(); } finally { // 应用程序退出时释放互斥锁 _mutex.ReleaseMutex(); _mutex.Dispose(); } } /// /// 应用程序退出时调用 /// /// 退出事件参数 protected override void OnExit(ExitEventArgs e) { ServiceProvider?.Dispose(); if (_mutex != null && !_mutex.SafeWaitHandle.IsClosed) { try { // 应用程序退出时释放互斥锁 _mutex.ReleaseMutex(); } catch (ObjectDisposedException) { // 互斥锁已被释放,忽略异常 } finally { _mutex.Dispose(); } } base.OnExit(e); } } }