C#WinForm 藏到系统托盘

来源:互联网 发布:java随机数生成1到100 编辑:程序博客网 时间:2024/04/29 21:05

1 添加Form1_Load事件-启动不显示图标

        private void Form1_Load(object sender, EventArgs e)        {            notifyIcon1.Visible = true;    //显示托盘图标            this.Hide();    //隐藏窗口        }
2 添加NotifyIcon控件-直接拖拽

3 为右键菜单ContextMenuStrip-显示和退出

        private void toolStripMenuItem1_Click(object sender, EventArgs e)        {            notifyIcon1.Visible = false;            this.Show();            WindowState = FormWindowState.Normal;            this.Focus();        }        private void toolStripMenuItem2_Click(object sender, EventArgs e)        {            Application.Exit();        }
4 关联右键菜单

5 NotifyIcon左键点击事件

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)        {            if (e.Button == System.Windows.Forms.MouseButtons.Left)            {                notifyIcon1.Visible = false;                this.Show();                WindowState = FormWindowState.Normal;                this.Focus();            }        }
6 窗体关闭和改变大小

        private void Form1_Resize(object sender, EventArgs e)        {            if (this.WindowState == FormWindowState.Minimized)    //最小化到系统托盘            {                notifyIcon1.Visible = true;    //显示托盘图标                this.Hide();    //隐藏窗口            }        }        //关闭事件-检测关闭位置[窗体上,还是托盘图标]        private void Form1_FormClosing(object sender, FormClosingEventArgs e)        {            //注意判断关闭事件Reason来源于窗体按钮,否则用菜单退出时无法退出!            if (e.CloseReason == CloseReason.UserClosing)            {                e.Cancel = true;    //取消"关闭窗口"事件                this.WindowState = FormWindowState.Minimized;    //使关闭时窗口向右下角缩小的效果                notifyIcon1.Visible = true;                this.Hide();                return;            }        }
*在关闭窗口事件中判断关闭原因/来源(e.CloseReason),若为CloseReason.UserClosing则为点击了窗口右上角的关闭按钮,否则可能是点击了"退出"菜单,则不执行隐藏到托盘的程序。










0 0
原创粉丝点击