C#:程序窗口关闭后,退到托盘图标

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace WindowsFormsApp21 {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }
//重写Closing(),关闭窗口时不退出程序,而是显示在托盘图标
//需要先在界面中添加一个 NotifyIcon控件,然后设置一个图标
//有右键菜单,则再添加一个ContextMenuStrip
        private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
            e.Cancel = true; //不退出程序
            this.WindowState = FormWindowState.Minimized; //最小化
            this.ShowInTaskbar = false; //在任务栏中不显示窗体
            this.notifyIcon1.Visible = true; //托盘图标可见
        }

        //托盘图标,鼠标左键显示回来原窗体,右键显示退出
        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e) {
            if (e.Button == MouseButtons.Left) {
                if (this.WindowState == FormWindowState.Minimized) {
                    this.Show();
                    this.WindowState = FormWindowState.Normal;
                    this.ShowInTaskbar = true;
                }
            }
            else {
                this.contextMenuStrip1.Show(Cursor.Position);
            }
        }

//退出菜单
        private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) {
            if (e.ClickedItem.Text.Equals("退出")) {
                this.Dispose();
                this.Close();
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38261174/article/details/85091396