WYVE

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

①在MainForm上托2个控件NotifyIcon和ContextMenuStrip。
②NotifyIcon:用于显示托盘。
a)先Choose Icon,作为托盘显示的图标;
b)设置属性ContextMenuStrip,关联右击后显示的菜单。
c)追加双击事件:

        private void mainNotifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.Visible)
            {
                this.WindowState = FormWindowState.Minimized;
                this.mainNotifyIcon.Visible = true;
                this.Hide();
            }
            else
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
                this.Activate();
            }

        }


③ContextMenuStrip:右击托盘显示的菜单。
a)追加3个Item,最大化,最小化,关闭。
b)追加最大化,最小化,关闭的处理代码。

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

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
            this.mainNotifyIcon.Visible = true;
            this.Show();
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Do you want to quit?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
            {
                this.mainNotifyIcon.Visible = false;
                this.Close();
                this.Dispose();
                System.Environment.Exit(System.Environment.ExitCode);
            }
        }


③重写主窗口的FormClosing方法,使Main上点关闭时,最小化到托盘。

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;

                this.WindowState = FormWindowState.Minimized;
                this.mainNotifyIcon.Visible = true;
                this.Hide();
                return;
            }
        }

 

posted on 2018-09-29 15:05  WYVE  阅读(878)  评论(0编辑  收藏  举报