namespace FixedAssetPrintAgent; internal sealed class PrintAgentApplicationContext : ApplicationContext { private readonly NotifyIcon _notifyIcon; private readonly PrintAgentRuntime _runtime; private readonly MainForm _mainForm; private bool _exitRequested; public PrintAgentApplicationContext() { var storageRoot = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "FixedAssetPrintAgent"); _runtime = new PrintAgentRuntime(storageRoot, Application.ProductVersion, Application.ExecutablePath); _runtime.StateChanged += HandleStateChanged; _mainForm = new MainForm(_runtime); _mainForm.FormClosing += HandleMainFormClosing; _notifyIcon = new NotifyIcon { Icon = SystemIcons.Application, Visible = true, Text = "固定资产打印助手" }; _notifyIcon.DoubleClick += (_, _) => ShowMainWindow(); _notifyIcon.ContextMenuStrip = BuildContextMenu(); _ = InitializeAsync(); } private async Task InitializeAsync() { try { await _runtime.InitializeAsync(); if (!_runtime.CurrentState.IsPaired) { ShowMainWindow(); } } catch (Exception ex) { MessageBox.Show( $"打印助手初始化失败:{ex.Message}", "打印助手", MessageBoxButtons.OK, MessageBoxIcon.Warning); ShowMainWindow(); } } private ContextMenuStrip BuildContextMenu() { var menu = new ContextMenuStrip(); menu.Items.Add("打开打印助手", null, (_, _) => ShowMainWindow()); menu.Items.Add("立即发送心跳", null, async (_, _) => await _runtime.HeartbeatNowAsync()); menu.Items.Add("立即轮询任务", null, async (_, _) => await _runtime.ClaimNowAsync()); menu.Items.Add(new ToolStripSeparator()); menu.Items.Add("退出", null, (_, _) => ExitApplication()); return menu; } private void HandleStateChanged(object? sender, PrintAgentRuntimeState state) { var summary = state.IsPaired ? string.IsNullOrWhiteSpace(state.Configuration.SelectedPrinterName) ? "待配置打印机" : "已配对" : "未配对"; var text = $"固定资产打印助手 - {summary}"; _notifyIcon.Text = text.Length > 63 ? text[..63] : text; } private void HandleMainFormClosing(object? sender, FormClosingEventArgs e) { if (_exitRequested) { return; } e.Cancel = true; _mainForm.Hide(); } private void ShowMainWindow() { if (_mainForm.Visible) { _mainForm.WindowState = FormWindowState.Normal; _mainForm.Activate(); return; } _mainForm.Show(); _mainForm.WindowState = FormWindowState.Normal; _mainForm.BringToFront(); _mainForm.Activate(); } private void ExitApplication() { _exitRequested = true; _notifyIcon.Visible = false; _mainForm.Close(); ExitThread(); } protected override void ExitThreadCore() { _notifyIcon.Visible = false; _notifyIcon.Dispose(); _runtime.Dispose(); base.ExitThreadCore(); } }