在C#中,NotifyIcon類用于在系統托盤中顯示一個圖標,并允許您與用戶交互。以下是NotifyIcon類的一些常見用法:
NotifyIcon notifyIcon = new NotifyIcon();
notifyIcon.Icon = new Icon("icon.ico"); // 設置圖標
notifyIcon.Text = "Notification"; // 設置文本
notifyIcon.Visible = true;
notifyIcon.MouseClick += NotifyIcon_MouseClick;
private void NotifyIcon_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
// 左鍵單擊事件處理
}
else if (e.Button == MouseButtons.Right)
{
// 右鍵單擊事件處理
}
}
ContextMenu contextMenu = new ContextMenu();
MenuItem menuItem = new MenuItem("Exit");
menuItem.Click += MenuItem_Click;
contextMenu.MenuItems.Add(menuItem);
notifyIcon.ContextMenu = contextMenu;
private void MenuItem_Click(object sender, EventArgs e)
{
// 退出應用程序
Application.Exit();
}
notifyIcon.BalloonTipText = "Hello, World!";
notifyIcon.BalloonTipTitle = "Notification";
notifyIcon.ShowBalloonTip(5000); // 顯示氣球提示,持續5秒
notifyIcon.Visible = false;
notifyIcon.Dispose();