1.拖一个NotifyIcon,一个ContextMenuStrip控件到主窗体中
2、设置notifyIcon1,一个contextMenuStrip1(如下图)
Icon为托盘图标,Text托盘显示文字,ContextMenuStrip右键菜单(退出),设置退出单击事件
3、添加主窗体关闭事件(FormClosing)
4、事件代码
private void MyService_FormClosing(object sender, FormClosingEventArgs e) { // 注意判断关闭事件reason来源于窗体按钮,否则用菜单退出时无法退出! if (e.CloseReason == CloseReason.UserClosing) { //取消"关闭窗口"事件 e.Cancel = true; //使关闭时窗口向右下角缩小的效果 this.WindowState = FormWindowState.Minimized; this.notifyIcon1.Visible = true; this.Hide(); return; } } private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) { if (this.Visible) { this.WindowState = FormWindowState.Minimized; this.notifyIcon1.Visible = true; this.Hide(); } else { this.Visible = true; this.WindowState = FormWindowState.Normal; this.Activate(); } } private void MenuItemTuichu_Click(object sender, EventArgs e) { this.notifyIcon1.Visible = false; this.Close(); this.Dispose(); System.Environment.Exit(0); }