Files
VacuumPressureMembranePoreS…/App.xaml.cs

75 lines
2.5 KiB
C#
Raw Normal View History

2026-04-11 08:51:47 +08:00
using MembranePoreTester.Communication;
2026-04-12 16:46:55 +08:00
using MembranePoreTester.Models;
using MembranePoreTester.Views;
2026-04-11 08:51:47 +08:00
using Microsoft.Extensions.Configuration;
using OfficeOpenXml;
using System;
2026-02-27 16:58:02 +08:00
using System.IO;
using System.Windows;
2026-02-26 17:07:19 +08:00
2026-02-27 16:03:49 +08:00
namespace MembranePoreTester
2026-02-26 17:07:19 +08:00
{
public partial class App : Application
{
2026-04-12 16:46:55 +08:00
public static UserRole CurrentUserRole { get; set; } = UserRole.Operator;
2026-02-27 16:58:02 +08:00
public static IPlcService PlcService { get; private set; }
public static PlcConfiguration PlcConfig { get; private set; }
2026-04-12 16:46:55 +08:00
protected override async void OnStartup(StartupEventArgs e)
2026-02-27 16:58:02 +08:00
{
2026-04-11 08:51:47 +08:00
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
2026-02-27 16:58:02 +08:00
base.OnStartup(e);
2026-04-12 16:46:55 +08:00
// 防止在登录窗口关闭时应用程序因没有窗口而自动退出
ShutdownMode = ShutdownMode.OnExplicitShutdown;
// 显示登录窗口,验证用户身份
var loginWindow = new LoginWindow();
if (loginWindow.ShowDialog() != true)
{
Shutdown();
return;
}
// 登录成功后初始化数据库和PLC连接
2026-03-02 18:50:30 +08:00
using var db = new AppDbContext();
2026-04-12 16:46:55 +08:00
db.Database.EnsureCreated();
2026-03-02 18:50:30 +08:00
2026-02-27 16:58:02 +08:00
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
var configuration = builder.Build();
PlcConfig = configuration.GetSection("PlcSettings").Get<PlcConfiguration>();
if (PlcConfig == null)
throw new InvalidOperationException("PLC settings missing in appsettings.json");
PlcService = new ModbusTcpPlcService(PlcConfig);
2026-04-10 18:54:06 +08:00
var plcService = App.PlcService as ModbusTcpPlcService;
try
{
await plcService.EnsureConnectedAsync();
}
catch (Exception ex)
{
MessageBox.Show($"PLC 连接失败:{ex.Message}");
}
2026-04-12 16:46:55 +08:00
// 启动主窗口,设置为应用程序的主窗口并恢复默认的退出模式
var mainWindow = new MainWindow();
MainWindow = mainWindow;
ShutdownMode = ShutdownMode.OnMainWindowClose;
mainWindow.Show();
2026-02-27 16:58:02 +08:00
}
protected override void OnExit(ExitEventArgs e)
{
(PlcService as IDisposable)?.Dispose();
base.OnExit(e);
}
2026-02-26 17:07:19 +08:00
}
2026-02-27 16:03:49 +08:00
}