c# 窗体最小化到托盘
c# winform最小化到托盘,也就是最小化到右下角,其实很简单,winform中有专门的控件。
下面是完整的代码,没太多需要解释的。
先在winform中添加notifyIcon控件,然后激活相应事件,添加代码。因为屏蔽了关闭窗体事件,可以设定一个全局变量bool变量来分辨是哪里引起的close事件。
注意添加Form的SizeChanged事件和NotifyIcon控件的DoubleClick事件
- //全家变量bool closeTag = true;
- //最小化
- private void form1_Resize(object sender, EventArgs e)
- {
- if (this.WindowState == FormWindowState.Minimized)
- {
- NormalToMinimized();
- }
- }
- //close时最小化
- private void form1_FormClosing(object sender, FormClosingEventArgs e)
- {
- e.Cancel = true;
- NormalToMinimized();
- }
- //单击显示窗体
- private void notifyIcon_MouseClick(object sender, MouseEventArgs e)
- {
- if (e.Button == MouseButtons.Left)
- {
- this.MinimizedToNormal();
- }
- }
- private void MinimizedToNormal()
- {
- this.Visible = true;
- this.WindowState = FormWindowState.Normal;
- notifyIcon.Visible = false;
- }
- private void NormalToMinimized()
- {
- this.WindowState = FormWindowState.Minimized;
- this.Visible = false;
- this.notifyIcon.Visible = true;
- }
- private void frmMain_FormClosing(object sender, FormClosingEventHandler e)
- {
- if (closeTag)
- {
- e.Cancel = true;
- NormalToMinimized();
- }
- }
- //托盘右键关闭事件
- private void 退出XToolStripMenuItem_Click(object sender, EventArgs e)
- {
- closeTag = false;
- Application.Exit();
- }