C# 窗口最小化到托盘及右键图标显示菜单

C#笔记 ningjian

1、需要在主界面添加2个控件

分别是NotifyIcon控件和ContextMenuStrip控件

2、NotifyIcon 设置ico图标

3、 在控件NotifyIcon中绑定上ContextMenuStrip控件

当运行程序时,就可以看见图标显示在右下角了

以下代码根据实际需要添加

 

      
 private void Form1_Load(object sender, EventArgs e)
        {

            ToolStripMenuItem itm2 = new ToolStripMenuItem();
            itm2.Name = "showthis";
            itm2.Text = "显示窗体";
            itm2.Click += ShowthisDialog;
            myMenu.Items.Add(itm2);

}

 private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (this.WindowState == FormWindowState.Normal)
                {
                    this.WindowState = FormWindowState.Minimized;
                    this.Hide();

                }
                else if (this.WindowState == FormWindowState.Minimized)
                {
                    this.Show();
                    this.WindowState = FormWindowState.Normal;
                    this.Activate();
                }
            }
            else if (e.Button == MouseButtons.Right)
            {

                myMenu.Show();

            }
        }

        private void exitPram_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("您确认要关闭吗?关闭后将无法接收和处理数据", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (result == DialogResult.Yes)
            {
                Application.Exit();
                // this.notifyIcon1.Dispose();
            }
        }

#region 显示隐藏窗体
        private void ShowthisDialog(object sender, EventArgs e)
        {
            this.Show();

            if (myMenu.Items.ContainsKey("showthis"))
            {
                myMenu.Items.RemoveByKey("showthis");
            }
            ToolStripMenuItem itm1 = new ToolStripMenuItem();
            itm1.Name = "hidethis";
            itm1.Text = "隐藏窗体";
            itm1.Click += HidethisDialog;
            myMenu.Items.Add(itm1);
            //this.Hide(); 
        }
        private void HidethisDialog(object sender, EventArgs e)
        {
            this.Hide();
            if (myMenu.Items.ContainsKey("hidethis"))
            {
                myMenu.Items.RemoveByKey("hidethis");
            }
            ToolStripMenuItem itm2 = new ToolStripMenuItem();
            itm2.Name = "showthis";
            itm2.Text = "显示窗体";
            itm2.Click += ShowthisDialog;
            myMenu.Items.Add(itm2);
        }
        private void startFrm_Shown(object sender, EventArgs e)
        {
            // textBox1.Text += "Form1_Shown" + System.Environment.NewLine;
            this.Hide();
        }
        #endregion

 

 

 

发表评论:

验证码