MainWindow.xaml.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Windows;
  3. using System.Windows.Forms;
  4. using Application = System.Windows.Application;
  5. using MessageBox = System.Windows.MessageBox;
  6. namespace athosRT
  7. {
  8. /// <summary>
  9. /// MainWindow.xaml 的交互逻辑
  10. /// </summary>
  11. public partial class MainWindow : Window
  12. {
  13. private NotifyIcon notifyIcon;
  14. public MainWindow()
  15. {
  16. InitializeComponent();
  17. DataContext = new MainWindowViewModel();
  18. this.ShowInTaskbar = false;
  19. this.WindowState = WindowState.Minimized;
  20. // 初始化 NotifyIcon
  21. var iconFromResources = Properties.Resources.RT2;
  22. notifyIcon = new NotifyIcon
  23. {
  24. Icon = iconFromResources, // 设置托盘图标文件路径
  25. Visible = true,
  26. Text = "JetEfem RT"
  27. };
  28. // 构建 ContextMenu 菜单项
  29. var contextMenu = new ContextMenuStrip();
  30. contextMenu.Items.Add("Show", null, (s, e) => ShowWindow());
  31. contextMenu.Items.Add("Exit", null, (s, e) => ExitApplication());
  32. notifyIcon.ContextMenuStrip = contextMenu; // 将菜单绑定至 NotifyIcon
  33. this.StateChanged += OnStateChanged; // 注册状态改变事件监听器
  34. }
  35. private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
  36. {
  37. MessageBoxResult result = MessageBox.Show("Are you sure quit the system ?", "JetEfem", MessageBoxButton.OKCancel, MessageBoxImage.None, MessageBoxResult.Cancel);
  38. System.Console.WriteLine(result);
  39. if (result == MessageBoxResult.Cancel)
  40. {
  41. e.Cancel = true;
  42. }
  43. }
  44. // 主界面完成关闭
  45. private void Window_Closed(object sender, System.EventArgs e)
  46. {
  47. Application.Current.Shutdown(0);
  48. Environment.Exit(0);
  49. }
  50. private void ShowWindow()
  51. {
  52. this.Show(); // 展示当前窗口
  53. this.WindowState = WindowState.Normal; // 恢复正常大小
  54. }
  55. private void ExitApplication()
  56. {
  57. notifyIcon.Visible = false; // 隐藏托盘图标以防资源泄漏
  58. notifyIcon.Dispose(); // 清理对象占用内存
  59. Application.Current.Shutdown(); // 关闭整个应用实例
  60. }
  61. private void OnStateChanged(object sender, EventArgs e)
  62. {
  63. if (this.WindowState == WindowState.Minimized && !IsMouseCaptured)
  64. {
  65. Hide(); // 当前窗口被最小化时自动隐藏它本身
  66. }
  67. }
  68. }
  69. }