在C#中使用NotifyIcon需要以下步骤:
添加NotifyIcon控件:在Windows窗体中,从工具箱中拖拽一个NotifyIcon控件到窗体上。
设置NotifyIcon属性:选中NotifyIcon控件,打开属性窗口,可以设置以下属性:
Icon:设置在托盘中显示的图标。
Text:设置鼠标悬停在托盘图标上显示的文本。
Visible:设置是否可见,默认为false。
ContextMenuStrip:设置右键菜单。
以下是一个简单的示例代码:
using System; using System.Windows.Forms; namespace NotifyIconExample { public partial class MainForm : Form { private NotifyIcon notifyIcon; private ContextMenuStrip contextMenuStrip; public MainForm() { InitializeComponent(); // 初始化NotifyIcon notifyIcon = new NotifyIcon(); notifyIcon.Icon = Properties.Resources.icon; notifyIcon.Text = "NotifyIcon Example"; notifyIcon.Visible = true; // 双击托盘图标时的事件处理 notifyIcon.DoubleClick += NotifyIcon_DoubleClick; // 初始化右键菜单 contextMenuStrip = new ContextMenuStrip(); ToolStripMenuItem openMenuItem = new ToolStripMenuItem("Open"); openMenuItem.Click += OpenMenuItem_Click; contextMenuStrip.Items.Add(openMenuItem); ToolStripMenuItem exitMenuItem = new ToolStripMenuItem("Exit"); exitMenuItem.Click += ExitMenuItem_Click; contextMenuStrip.Items.Add(exitMenuItem); // 设置右键菜单 notifyIcon.ContextMenuStrip = contextMenuStrip; } private void NotifyIcon_DoubleClick(object sender, EventArgs e) { // 双击托盘图标时,打开或关闭主窗体 if (WindowState == FormWindowState.Minimized) { WindowState = FormWindowState.Normal; } else { WindowState = FormWindowState.Minimized; } } private void OpenMenuItem_Click(object sender, EventArgs e) { // 打开主窗体 WindowState = FormWindowState.Normal; } private void ExitMenuItem_Click(object sender, EventArgs e) { // 退出应用程序 Application.Exit(); } protected override void OnFormClosing(FormClosingEventArgs e) { // 在窗体关闭时,将NotifyIcon资源释放 notifyIcon.Visible = false; notifyIcon.Dispose(); base.OnFormClosing(e); } } }
以上代码实现了一个简单的NotifyIcon示例,包含了双击托盘图标打开或关闭主窗体的功能,以及右键菜单中的打开和退出功能。