背景
现在很多程序都有这样的托盘程序
窗体关闭时,并不真正关闭程序,只是任务栏不显示该应用程序,在右下侧托盘里显示;
双击托盘,窗体还原;
右击窗体,出现托盘菜单,实现最小化,最大户,还原,退出等。
这样的功能C#winform怎样实现呢 ?
实现
WinForm中托盘菜单由NotifyIcon控件来实现,右键菜单由contextMenuStrip来实现,我们将二者相关联,即可实现我们所期望功能的托盘程序。
添加控件
我们在需要托盘的form界面上拖入NotifyIcon和一个ContextMenuStrip控件。
设置控件信息
设置控件的属性为我们期望的功能,
如本例中NotifyIcon控件名NAME为“mainNotifyIcon”,ContextMenuStrip控件名NAME为”mainNotifyContextMenuStrip”)
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.1private 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// 最小化// 添加日期 -- -07-29 21:40private void toolStripMenuItemMinimize_Click(object sender, EventArgs e){this.WindowState = FormWindowState.Minimized;this.mainNotifyIcon.Visible = true;this.Hide();}// 添加托盘程序右键菜单项// 版本更新自1.0.1// 最大化// 添加日期 -- -07-29 21:41private void toolStripMenuItemMaximize_Click(object sender, EventArgs e){this.WindowState = FormWindowState.Maximized;this.mainNotifyIcon.Visible = true;this.Show();}// 添加托盘程序右键菜单项// 版本更新自1.0.1// 还原// 添加日期 -- -07-29 21:43private void toolStripMenuItemNormal_Click(object sender, EventArgs e){this.WindowState = FormWindowState.Normal;this.mainNotifyIcon.Visible = true;//this.m_cartoonForm.CartoonShowNormal();this.Show();}// 添加托盘程序右键菜单项// 版本更新自1.0.1// 退出// 添加日期 -- -07-29 21:44private 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); }}}