C#之使⽤NotifyIcon实现任务栏托盘菜单,图标闪烁效果及⽓泡
提⽰
很多程序是只需要后台运⾏的,甚⾄不需要⾃⼰的应⽤界⾯。NotifyIcon提供了程序在任务栏的显⽰功能
程序下载链接如下:
1.创建⼀个项⽬,向窗体中添加NotifyIcon控件和ContextMenuStrip控件;
2.为ContextMenuStrip控件添加⼦项;
3.选择NotifyIcon控件,在其属性窗⼝中将ContextMenuStrip属性设置为添加到窗体上的ContextMenuStrip控件,并为Icon属性设置图⽚。注:必须为NotifyIcon控件的Icon属性设置图标,否则是看不到的
代码:
1private void显⽰ToolStripMenuItem_Click(object sender, EventArgs e)
2        {
3this.Visible = true;
4        }
5
6private void设置ToolStripMenuItem_Click(object sender, EventArgs e)
7        {
8this.Visible = false;
9        }
10
11private void退出ToolStripMenuItem_Click(object sender, EventArgs e)
12        {
13            Application.Exit();
14        }
效果图:
2.图标的闪烁效果
在图标闪烁中提到,给NotifyIcon赋予⼀个ICON可以控制使其在任务栏显⽰,闪烁的效果是加上⼀个空⽩的图标,正常图标与空⽩图标的切换进⽽实现闪烁的效果。
注:不能使⽤清除icon的⽅法,否则图标是在该位置清除,会引起其他图标的移动,空⽩图标起到占位
的作⽤
代码如下:
说明:property是vs的⼀个资源管理功能,可以存储系统图标及⼀些常量
1private Icon blank = Properties.Resources.blank;
2private Icon normal = al;
menustrip和toolstrip3private bool _status = true;
4private bool _isBlink = false;
右键菜单控制图标是不是显⽰
1private void toolStripMenuItem1_Click(object sender, EventArgs e)
2    {
3if (_isBlink == false)
4        {
5            _isBlink = true;
6            timer1.Enabled = true;
7            timer1.Start();
8        }
9else
10        {
11            _isBlink = false;
12            timer1.Stop();
13
14            notifyIcon1.ShowBalloonTip(5000, "提⽰", "关闭闪烁效果!", ToolTipIcon.Info);
15        }
16    }
定时器中修改图标的状态,定时反转图标
1private void timer1_Tick(object sender, EventArgs e)
2    {
3if (_status)
4            notifyIcon1.Icon = normal;
5else
6            notifyIcon1.Icon = blank;
7
8        _status = !_status;
9    }
⽓泡提⽰:
notifyIcon1.ShowBalloonTip(5000, "提⽰", "关闭闪烁效果!", ToolTipIcon.Info);