要求:
1 程序启动时,无系统托盘
2 程序最小化时,显示托盘,且程序隐藏
3 双击系统托盘,显示主界面,托盘隐藏
4 系统托盘右键,点击显示和退出按钮,主程序显示和退出
代码;
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace SystemIcon { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void Form1_Resize(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Minimized) {//最小化时 显示系统托盘,主界面隐藏 notifyIcon1.Visible = true; this.Visible = false; } else { //隐藏系统托盘 notifyIcon1.Visible = false; } } private void notifyIcon1_DoubleClick(object sender, EventArgs e) { this.Visible = true; //显示主窗口 this.WindowState = FormWindowState.Normal; this.Activate();//获得焦点 notifyIcon1.Visible = false;//隐藏托盘 } private void 显示ToolStripMenuItem_Click(object sender, EventArgs e) { // 显示主程序 notifyIcon1_DoubleClick(sender, e); } private void 退出ToolStripMenuItem_Click(object sender, EventArgs e) { //退出 this.Close(); Application.Exit(); } } }
说明;
1 添加NotifyIcon 和 ContextMenuStrip
2 使用NotifyIcon的ContextMenuStrip属性关联ContextMenuStrip