C# 公共控件之NotifyIcon 将窗口最小化到托盘

1、设置窗体和notifyIcon属性

notifyIcon  ,添加contextMenuStrip控件并集成到notifyIcon  的ContextMenuStrip上。

窗体

2、代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;

namespace DemoCSDN
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.notifyIcon1.Visible = false;
        }

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

        private void 打开主界面ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.Visible)
            {
                this.Hide();
            }
            else
            {
                this.notifyIcon1.Visible = false;
                this.Visible = true;
                WindowState = FormWindowState.Normal;
                this.Show();
            }
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                this.notifyIcon1.Visible = true;
                this.notifyIcon1.ShowBalloonTip(30, "注意", "大家好,这是一个事例", ToolTipIcon.Info);
            }
        }

        private void Form1_MinimumSizeChanged(object sender, EventArgs e)
        {
            this.Hide();
            this.Visible = false;
            WindowState = FormWindowState.Minimized;
        }     
    }
}

3、操作界面

鼠标移动到图标处显示 TestIcon ,由于设置了 notifyIcon的Text属性

鼠标右键图标,弹出菜单(contextMenuStrip),分别建立了相应的事件

扫描二维码关注公众号,回复: 3631157 查看本文章

双击图标,弹出正常操作界面

猜你喜欢

转载自blog.csdn.net/zhuxipan1990/article/details/83096268