WinForm 实现最小化任务栏托盘

步骤:

1. 在Form上添加一个 NotifyIcon 控件,无需设置属性,当时如果想要在最小化到任务栏可以点右键菜单,那还需要添加一个ContextMenuStrip菜单控件,然后把 NotifyIcon的ContextMenuStrip属性设置为菜单控件即可。

2.在 NotifyIcon  的DoubleClick 事件里,添加以下代码:

private void mainNotifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //双击显示主界面
            if (this.Visible)
            {
                this.WindowState = FormWindowState.Minimized;
                this.mainNotifyIcon.Visible = true;
                this.Hide();
            }
            else
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
                this.Activate();
            }
        }

3.在窗体 Form 的Closing 事件添加以下代码:

private void frMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 注意判断关闭事件reason来源于窗体按钮,否则用菜单退出时无法退出!
            if (e.CloseReason == CloseReason.UserClosing)
            {
                //取消"关闭窗口"事件
                e.Cancel = true; // 取消关闭窗体 

                //使关闭时窗口向右下角缩小的效果
                this.WindowState = FormWindowState.Minimized;
                this.mainNotifyIcon.Visible = true;
                //this.m_cartoonForm.CartoonClose();
                this.Hide();
                return;
            } 
        }

这样就搞定了。

posted on 2018-08-14 16:04  lpq22221314  阅读(340)  评论(0编辑  收藏  举报

导航