1. 程式人生 > >C# 公共控制元件之NotifyIcon 將視窗最小化到托盤

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),分別建立了相應的事件

雙擊圖示,彈出正常操作介面