MainWindow.xaml.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Diagnostics;
  3. using System.Reflection;
  4. using System.Windows;
  5. using System.Windows.Interop;
  6. namespace FastGithub.UI
  7. {
  8. /// <summary>
  9. /// MainWindow.xaml 的交互逻辑
  10. /// </summary>
  11. public partial class MainWindow : Window
  12. {
  13. private readonly System.Windows.Forms.NotifyIcon notifyIcon;
  14. private const string FASTGITHUB_UI = "FastGithub.UI";
  15. private const string RELEASES_URI = "https://github.com/dotnetcore/FastGithub/releases";
  16. public MainWindow()
  17. {
  18. InitializeComponent();
  19. var upgrade = new System.Windows.Forms.MenuItem("检测更新(&U)");
  20. upgrade.Click += (s, e) => Process.Start(RELEASES_URI);
  21. var exit = new System.Windows.Forms.MenuItem("关闭应用(&C)");
  22. exit.Click += (s, e) => this.Close();
  23. var version = this.GetType().Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
  24. this.Title = $"{FASTGITHUB_UI} v{version}";
  25. this.notifyIcon = new System.Windows.Forms.NotifyIcon
  26. {
  27. Visible = true,
  28. Text = FASTGITHUB_UI,
  29. ContextMenu = new System.Windows.Forms.ContextMenu(new[] { upgrade, exit }),
  30. Icon = System.Drawing.Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath)
  31. };
  32. this.notifyIcon.MouseClick += (s, e) =>
  33. {
  34. if (e.Button == System.Windows.Forms.MouseButtons.Left)
  35. {
  36. this.Show();
  37. this.Activate();
  38. this.WindowState = WindowState.Normal;
  39. }
  40. };
  41. }
  42. /// <summary>
  43. /// 拦截最小化事件
  44. /// </summary>
  45. /// <param name="e"></param>
  46. protected override void OnSourceInitialized(EventArgs e)
  47. {
  48. base.OnSourceInitialized(e);
  49. var hwndSource = (HwndSource)PresentationSource.FromVisual(this);
  50. hwndSource.AddHook(WndProc);
  51. IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
  52. {
  53. const int WM_SYSCOMMAND = 0x112;
  54. const int SC_MINIMIZE = 0xf020;
  55. const int SC_CLOSE = 0xf060;
  56. if (msg == WM_SYSCOMMAND)
  57. {
  58. if (wParam.ToInt32() == SC_MINIMIZE || wParam.ToInt32() == SC_CLOSE)
  59. {
  60. this.Hide();
  61. handled = true;
  62. }
  63. }
  64. return IntPtr.Zero;
  65. }
  66. }
  67. /// <summary>
  68. /// 关闭时
  69. /// </summary>
  70. /// <param name="e"></param>
  71. protected override void OnClosed(EventArgs e)
  72. {
  73. this.notifyIcon.Icon = null;
  74. this.notifyIcon.Dispose();
  75. base.OnClosed(e);
  76. }
  77. }
  78. }