TrayIconManager.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Windows.Forms;
  8. namespace LocalhostMES.Core
  9. {
  10. public class TrayIconManager : IDisposable
  11. {
  12. private NotifyIcon trayIcon;
  13. private ContextMenuStrip trayMenu;
  14. public event EventHandler OnExit;
  15. public event EventHandler OnSettings;
  16. public event EventHandler OnAbout;
  17. public TrayIconManager()
  18. {
  19. InitializeTrayIcon();
  20. }
  21. private void InitializeTrayIcon()
  22. {
  23. // 创建托盘菜单
  24. trayMenu = new ContextMenuStrip();
  25. // 添加菜单项
  26. ToolStripMenuItem settingsItem = new ToolStripMenuItem("设置");
  27. settingsItem.Click += (s, e) => OnSettings?.Invoke(this, e);
  28. ToolStripMenuItem aboutItem = new ToolStripMenuItem("关于");
  29. aboutItem.Click += (s, e) => OnAbout?.Invoke(this, e);
  30. ToolStripMenuItem exitItem = new ToolStripMenuItem("退出");
  31. exitItem.Click += (s, e) => OnExit?.Invoke(this, e);
  32. trayMenu.Items.Add(settingsItem);
  33. trayMenu.Items.Add(new ToolStripSeparator());
  34. trayMenu.Items.Add(aboutItem);
  35. trayMenu.Items.Add(new ToolStripSeparator());
  36. trayMenu.Items.Add(exitItem);
  37. // 创建托盘图标
  38. trayIcon = new NotifyIcon
  39. {
  40. Text = "本地MES",
  41. Icon = CreateTrayIcon(),
  42. ContextMenuStrip = trayMenu,
  43. Visible = false
  44. };
  45. // 双击托盘图标事件
  46. trayIcon.DoubleClick += (s, e) => OnSettings?.Invoke(this, e);
  47. // 气泡提示事件
  48. trayIcon.BalloonTipClicked += (s, e) => OnAbout?.Invoke(this, e);
  49. }
  50. private Icon CreateTrayIcon()
  51. {
  52. // 创建一个简单的图标(可以使用资源文件或外部图标)
  53. Bitmap bitmap = new Bitmap(16, 16);
  54. using ( Graphics g = Graphics.FromImage(bitmap) )
  55. {
  56. g.Clear(Color.Transparent);
  57. g.FillRectangle(Brushes.Blue, 2, 2, 4, 12); // 第一个屏幕
  58. g.FillRectangle(Brushes.Green, 8, 2, 4, 12); // 第二个屏幕
  59. g.FillEllipse(Brushes.White, 6, 6, 4, 4); // 鼠标指针
  60. }
  61. return Icon.FromHandle(bitmap.GetHicon());
  62. }
  63. public void Show()
  64. {
  65. trayIcon.Visible = true;
  66. // 显示启动提示
  67. trayIcon.ShowBalloonTip(1000, "本地MES",
  68. "程序已启动", ToolTipIcon.Info);
  69. }
  70. public void ShowNotification(string title, string message)
  71. {
  72. trayIcon.ShowBalloonTip(1000, title, message, ToolTipIcon.Info);
  73. }
  74. public void Dispose()
  75. {
  76. if ( trayIcon != null )
  77. {
  78. trayIcon.Visible = false;
  79. trayIcon.Dispose();
  80. }
  81. if ( trayMenu != null )
  82. {
  83. trayMenu.Dispose();
  84. }
  85. }
  86. }
  87. }