C# Winform托盘显示、关闭退出

Winform设置托盘程序,托盘显示

 

1.拖一个NotifyIcon,一个ContextMenuStrip控件到主窗体中

2、设置notifyIcon1,一个contextMenuStrip1(如下图)

Icon为托盘图标,Text托盘显示文字,ContextMenuStrip右键菜单(退出),设置退出单击事件

3、添加主窗体关闭事件(FormClosing)

4、事件代码

复制代码
复制代码
        private void MyService_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 注意判断关闭事件reason来源于窗体按钮,否则用菜单退出时无法退出!
            if (e.CloseReason == CloseReason.UserClosing)
            {
                //取消"关闭窗口"事件
                e.Cancel = true;
                //使关闭时窗口向右下角缩小的效果
                this.WindowState = FormWindowState.Minimized;   
                this.notifyIcon1.Visible = true;
                this.Hide();
                return;
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.Visible)
            {
                this.WindowState = FormWindowState.Minimized;
                this.notifyIcon1.Visible = true;
                this.Hide();
            }
            else
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;                
                this.Activate();
            }
        }

        private void MenuItemTuichu_Click(object sender, EventArgs e)
        {
            this.notifyIcon1.Visible = false;
            this.Close();
            this.Dispose();
            System.Environment.Exit(0);
        }
复制代码
复制代码

 

 

经验:需要注意的是,控件之间相互关联!

posted on 2022-06-17 11:06  8888888888888  阅读(646)  评论(0)    收藏  举报

< 2025年7月 >
29 30 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31 1 2
3 4 5 6 7 8 9

导航

Live2D
点击右上角即可分享
微信分享提示