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;//在通知区域隐藏

        //    }

        }

    }

}

 

你可能感兴趣的:(WinForm)