系統匣程式在工作列通知區顯示圖示,佔用螢幕空間小、直觀且可附加多功能選單。.NET Framework WinForms 提供 NotifyIcon 元件,極簡化開發。
方法一:覆寫 OnActivated 呼叫 Hide()。
方法二 (本文採用):初始化時設定 MaximizeBox = false; MinimizeBox = false; WindowState = FormWindowState.Minimized;。
private Icon mNetTrayIcon = new Icon("Tray.ico");
TrayIcon.Icon = mNetTrayIcon;
編譯後目錄必須存在 Tray.ico。
TrayIcon.Text = "用 Visual C# 做系統匣程式\n作者:馬金虎於 2001.12.08";
MenuItem[] mnuItms = new MenuItem[3];
mnuItms[0] = new MenuItem { Text = "用 Visual C# 做系統匣程式!", Click += showmessage };
mnuItms[1] = new MenuItem("-");
mnuItms[2] = new MenuItem { Text = "離開系統", Click += ExitSelect, DefaultItem = true };
notifyiconMnu = new ContextMenu(mnuItms);
TrayIcon.ContextMenu = notifyiconMnu;
using System;
using System.Drawing;
using System.Windows.Forms;
public class Tray : Form
{
private Icon mNetTrayIcon = new Icon("Tray.ico");
private NotifyIcon TrayIcon;
private ContextMenu notifyiconMnu;
public Tray()
{
InitializeComponent();
Initializenotifyicon();
}
private void Initializenotifyicon()
{
TrayIcon = new NotifyIcon();
TrayIcon.Icon = mNetTrayIcon;
TrayIcon.Text = "用 Visual C# 做系統匣程式\n作者:馬金虎於 2001.12.08";
TrayIcon.Visible = true;
TrayIcon.Click += click;
MenuItem[] mnuItms = new MenuItem[3];
mnuItms[0] = new MenuItem { Text = "用 Visual C# 做系統匣程式!" };
mnuItms[0].Click += showmessage;
mnuItms[1] = new MenuItem("-");
mnuItms[2] = new MenuItem { Text = "離開系統", DefaultItem = true };
mnuItms[2].Click += ExitSelect;
notifyiconMnu = new ContextMenu(mnuItms);
TrayIcon.ContextMenu = notifyiconMnu;
}
public void click(object sender, EventArgs e) { MessageBox.Show("Visual C# 撰寫系統匣程式事件回應"); }
public void showmessage(object sender, EventArgs e) { MessageBox.Show("你點擊了選單第一個選項"); }
public void ExitSelect(object sender, EventArgs e) { TrayIcon.Visible = false; this.Close(); }
public override void Dispose() { base.Dispose(); }
private void InitializeComponent()
{
this.SuspendLayout();
this.AutoScaleBaseSize = new Size(5, 13);
this.ClientSize = new Size(320, 56);
this.ControlBox = false;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.WindowState = FormWindowState.Minimized;
this.Name = "tray";
this.ShowInTaskbar = false;
this.Text = "用 Visual C# 做系統匣程式!";
this.ResumeLayout(false);
}
[STAThread]
static void Main() { Application.Run(new Tray()); }
}
Visual C# 配合 .NET Framework SDK,讓系統匣程式開發變得輕鬆愉快。IDE 只是鑰匙,豐富的類別庫才是舞臺。