C#一行代码实现(01)最小化到通知区域
- 2020 年 10 月 24 日
- 笔记
- C#一行代码实现
主要功能
- 实现
Winform
程序最小化后,隐藏任务栏显示,在通知区域显示。左键点击通知区域图标,可以弹出菜单,包含开机启动
和退出程序
,可以根据需求进行定制。
一行代码
private void Form1_Load(object sender, EventArgs e)
{
this.ExAddNotifyIcon();
}
代码封装
/// <summary>
/// 添加通知图标,左键点击切换窗口显示,右键点击弹出菜单
/// </summary>
/// <param name="form"></param>
/// <param name="tipText"></param>
/// <param name="timeout"></param>
/// <param name="tipIcon"></param>
/// <returns></returns>
public static NotifyIcon ExAddNotifyIcon(this Form form, string tipText = "程序最小化至后台运行,点击图标显示程序", int timeout = 3000, ToolTipIcon tipIcon = ToolTipIcon.Info)
{
NotifyIcon notifyIcon = new NotifyIcon();
notifyIcon.Icon = form.Icon;
notifyIcon.Visible = true;
notifyIcon.Text = form.Text;
notifyIcon.BalloonTipText = form.Text;
notifyIcon.MouseClick += (sender, args) =>
{
if (args.Button == MouseButtons.Left)
{
if (!form.Visible)
{
form.Show();
form.WindowState = FormWindowState.Normal;
form.TopMost = true;
form.TopMost = false;
}
else
{
form.WindowState = FormWindowState.Minimized;
form.Hide();
}
}
};
notifyIcon.ContextMenu = new ContextMenu(new MenuItem[]
{
new MenuItem("开机启动", (sender, args) => { ((MenuItem) sender).Checked = form.ExSwitchRunOnSystemStart(); })
{
Checked = form.ExIsRunOnSystemStart()
},
new MenuItem("退出程序", (sender, args) => { form.Close(); }),
});
form.SizeChanged += (sender, args) =>
{
if (form.WindowState == FormWindowState.Minimized)
{
form.Hide();
notifyIcon.ShowBalloonTip(timeout, form.Text, tipText, tipIcon);
}
};
form.FormClosed += (sender, args) => { notifyIcon.Dispose(); };
return notifyIcon;
}
声明