在C# WinForms中,NotifyIcon控件用于在系统托盘中显示图标和弹出菜单。它通常用于在后台运行的应用程序中提供通知和快速访问功能。
以下是一个简单的示例,演示如何在WinForms中使用NotifyIcon控件:
- 在Visual Studio中创建一个新的WinForms应用程序项目。
- 在窗体设计器中,将NotifyIcon控件拖放到窗体上。
- 在代码中,您可以使用NotifyIcon控件的Icon属性来设置要显示的图标,使用Text属性来设置鼠标悬停时显示的文本。
- 您还可以使用ContextMenu属性来设置弹出菜单,并在菜单项的Click事件处理程序中处理用户的操作。
以下是一个示例代码,演示如何在WinForms中使用NotifyIcon控件:
using System;
using System.Windows.Forms;
namespace WinFormsApp
{
public partial class MainForm : Form
{
private NotifyIcon notifyIcon;
private ContextMenu contextMenu;
public MainForm()
{
InitializeComponent();
// 创建NotifyIcon控件
notifyIcon = new NotifyIcon();
notifyIcon.Icon = Properties.Resources.AppIcon;
notifyIcon.Text = "My Application";
// 创建弹出菜单
contextMenu = new ContextMenu();
contextMenu.MenuItems.Add("显示窗体", ShowFormMenuItem_Click);
contextMenu.MenuItems.Add("退出", ExitMenuItem_Click);
// 将弹出菜单关联到NotifyIcon控件
notifyIcon.ContextMenu = contextMenu;
// 显示NotifyIcon控件
notifyIcon.Visible = true;
}
private void ShowFormMenuItem_Click(object sender, EventArgs e)
{
// 显示窗体
this.Show();
}
private void ExitMenuItem_Click(object sender, EventArgs e)
{
// 退出应用程序
Application.Exit();
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
// 隐藏窗体并取消关闭操作
this.Hide();
e.Cancel = true;
}
}
}
在示例中,创建了一个名为MainForm的窗体,并在其上添加了一个NotifyIcon控件。使用
Properties.Resources.AppIcon设置了NotifyIcon的图标,并设置了文本为"My Application"。
创建了一个ContextMenu对象作为弹出菜单,并添加了两个菜单项:"显示窗体"和"退出"。在菜单项的Click事件处理程序中,分别处理了显示窗体和退出应用程序的操作。
在窗体的FormClosing事件处理程序中,隐藏了窗体并取消了关闭操作,以便窗体可以最小化到系统托盘而不是关闭。