要求:
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