| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- using System;
- using System.Collections.Generic;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- namespace LocalhostMES.Core
- {
- public class TrayIconManager : IDisposable
- {
- private NotifyIcon trayIcon;
- private ContextMenuStrip trayMenu;
- public event EventHandler OnExit;
- public event EventHandler OnSettings;
- public event EventHandler OnAbout;
- public TrayIconManager()
- {
- InitializeTrayIcon();
- }
- private void InitializeTrayIcon()
- {
- // 创建托盘菜单
- trayMenu = new ContextMenuStrip();
- // 添加菜单项
- ToolStripMenuItem settingsItem = new ToolStripMenuItem("设置");
- settingsItem.Click += (s, e) => OnSettings?.Invoke(this, e);
- ToolStripMenuItem aboutItem = new ToolStripMenuItem("关于");
- aboutItem.Click += (s, e) => OnAbout?.Invoke(this, e);
- ToolStripMenuItem exitItem = new ToolStripMenuItem("退出");
- exitItem.Click += (s, e) => OnExit?.Invoke(this, e);
- trayMenu.Items.Add(settingsItem);
- trayMenu.Items.Add(new ToolStripSeparator());
- trayMenu.Items.Add(aboutItem);
- trayMenu.Items.Add(new ToolStripSeparator());
- trayMenu.Items.Add(exitItem);
- // 创建托盘图标
- trayIcon = new NotifyIcon
- {
- Text = "本地MES",
- Icon = CreateTrayIcon(),
- ContextMenuStrip = trayMenu,
- Visible = false
- };
- // 双击托盘图标事件
- trayIcon.DoubleClick += (s, e) => OnSettings?.Invoke(this, e);
- // 气泡提示事件
- trayIcon.BalloonTipClicked += (s, e) => OnAbout?.Invoke(this, e);
- }
- private Icon CreateTrayIcon()
- {
- // 创建一个简单的图标(可以使用资源文件或外部图标)
- Bitmap bitmap = new Bitmap(16, 16);
- using ( Graphics g = Graphics.FromImage(bitmap) )
- {
- g.Clear(Color.Transparent);
- g.FillRectangle(Brushes.Blue, 2, 2, 4, 12); // 第一个屏幕
- g.FillRectangle(Brushes.Green, 8, 2, 4, 12); // 第二个屏幕
- g.FillEllipse(Brushes.White, 6, 6, 4, 4); // 鼠标指针
- }
- return Icon.FromHandle(bitmap.GetHicon());
- }
- public void Show()
- {
- trayIcon.Visible = true;
- // 显示启动提示
- trayIcon.ShowBalloonTip(1000, "本地MES",
- "程序已启动", ToolTipIcon.Info);
- }
- public void ShowNotification(string title, string message)
- {
- trayIcon.ShowBalloonTip(1000, title, message, ToolTipIcon.Info);
- }
- public void Dispose()
- {
- if ( trayIcon != null )
- {
- trayIcon.Visible = false;
- trayIcon.Dispose();
- }
- if ( trayMenu != null )
- {
- trayMenu.Dispose();
- }
- }
- }
- }
|