WpfApp/App.xaml.cs

112 lines
4.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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