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

 

1、设置窗体和notifyIcon属性

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

C# 公共控件之NotifyIcon 将窗口最小化到托盘_第1张图片

窗体

C# 公共控件之NotifyIcon 将窗口最小化到托盘_第2张图片

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属性

C# 公共控件之NotifyIcon 将窗口最小化到托盘_第3张图片

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

C# 公共控件之NotifyIcon 将窗口最小化到托盘_第4张图片

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

C# 公共控件之NotifyIcon 将窗口最小化到托盘_第5张图片

你可能感兴趣的:(C#)