背景现在很多程序都有这样的托盘程序 实现WinForm中托盘菜单由NotifyIcon控件来实现,右键菜单由contextMenuStrip来实现,我们将二者相关联,即可实现我们所期望功能的托盘程序。 添加控件我们在需要托盘的form界面上拖入NotifyIcon和一个ContextMenuStrip控件。 设置控件信息设置控件的属性为我们期望的功能, Icon为托盘图标,Text托盘显示文字,ContextMenuStrip右键菜单(退出),设置退出单击事件,我们将mainNotifyIcon的ContextMenuStrip属性设置为mainNotifyContextMenuStrip,即可实现该托盘与右键菜单的关联,在托盘上右键即出现右键菜单 我们开始添加右键菜单的各个选项,比如:最小化,最大化,还原,退出等 实现事件关联添加主窗体关闭事件(FormClosing) // 只有Form_Closing事件中 e.Cancel可以用。 // 你的是Form_Closed事件。 Form_Closed事件时窗口已关了 ,Cancel没用了; // Form_Closing是窗口即将关闭时询问你是不是真的关闭才有Cancel事件 private void MainWindow_FormClosing(object sender, FormClosingEventArgs e) { // 注意判断关闭事件reason来源于窗体按钮,否则用菜单退出时无法退出! if (e.CloseReason == CloseReason.UserClosing) { //取消'关闭窗口'事件 e.Cancel = true; // 取消关闭窗体 //使关闭时窗口向右下角缩小的效果 this.WindowState = FormWindowState.Minimized; this.mainNotifyIcon.Visible = true; //this.m_cartoonForm.CartoonClose(); this.Hide(); return; } }
这样我们就实现了单击关闭时,不真正关闭程序,而是将主界面隐藏HIDE掉,同时开始显示托盘菜单。 实现双击托盘打开主程序 // 添加托盘程序 // 版本更新自1.0.1 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(); } }
右键菜单实现最小化最大化还原和退出// 添加托盘程序右键菜单项 // 版本更新自1.0.1 // 最小化 // 添加日期 -- 2015-07-29 21:40 private void toolStripMenuItemMinimize_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; this.mainNotifyIcon.Visible = true; this.Hide(); } // 添加托盘程序右键菜单项 // 版本更新自1.0.1 // 最大化 // 添加日期 -- 2015-07-29 21:41 private void toolStripMenuItemMaximize_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Maximized; this.mainNotifyIcon.Visible = true; this.Show(); } // 添加托盘程序右键菜单项 // 版本更新自1.0.1 // 还原 // 添加日期 -- 2015-07-29 21:43 private void toolStripMenuItemNormal_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Normal; this.mainNotifyIcon.Visible = true; //this.m_cartoonForm.CartoonShowNormal(); this.Show(); } // 添加托盘程序右键菜单项 // 版本更新自1.0.1 // 退出 // 添加日期 -- 2015-07-29 21:44 private async void toolStripMenuItemQuit_Click(object sender, EventArgs e) { if (MessageBox.Show('你确定要退出?', '系统提示', MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { this.mainNotifyIcon.Visible = false; this.Close(); this.Dispose(); System.Environment.Exit(System.Environment.ExitCode); } } }
|
|
来自: goodwangLib > 《C#托盘》