C#- Winform最小化到托盘

实现前先拉一个notifyIcon控件,在Icon属性中加入一个ICON小图标,然后具体的代码实现如下:

复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace NotifyDemo
{
    public partial class Form1 : Form
    {
        private ContextMenu notifyiconMnu;

        public Form1()
        {
            
            InitializeComponent();
        }

        //通知区域的菜单
        public void Initializenotifyicon()
        {
            //定义一个MenuItem数组,并把此数组同时赋值给ContextMenu对象 
            MenuItem[] mnuItms = new MenuItem[3];
            mnuItms[0] = new MenuItem();
            mnuItms[0].Text = "显示窗口";
            mnuItms[0].Click += new System.EventHandler(this.notifyIcon1_funone);

            mnuItms[1] = new MenuItem("-");

            mnuItms[2] = new MenuItem();
            mnuItms[2].Text = "退出系统";
            mnuItms[2].Click += new System.EventHandler(this.notifyIcon1_funtwo);
            mnuItms[2].DefaultItem = true;

            notifyiconMnu = new ContextMenu(mnuItms);
            notifyIcon1.ContextMenu = notifyiconMnu;
        }

        //调用函数1
        public void notifyIcon1_funone(object sender, System.EventArgs e)
        {
            MessageBox.Show("funOne");
        }

        //调用函数2
        public void notifyIcon1_funtwo(object sender, System.EventArgs e)
        {
            MessageBox.Show("funTwo");
        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized) //判断是否最小化
            {
                this.notifyIcon1.Visible = true;//在通知区域显示
                this.Hide();//窗体隐藏
                this.ShowInTaskbar = false;//不显示在任务栏

                Initializenotifyicon();
            }

        }


        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
        //    if (e.Button == System.Windows.Forms.MouseButtons.Right)
        //    {
        //        this.Show();//窗体显示
        //        this.ShowInTaskbar = true;//在任务栏显示
        //        this.WindowState = FormWindowState.Normal;
        //        this.notifyIcon1.Visible = false;//在通知区域隐藏
        //    }
        }
    }
}
复制代码

 

posted @   春天又来了  阅读(244)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示