讓WPF應用最小到系統托盤?可以調用System.Windows.Forms.NotifyIcon來實現,下面是示例代碼:

public partial class MainWindow : Window { private NotifyIcon notifyIcon; public MainWindow() { InitializeComponent(); this.notifyIcon = new NotifyIcon(); this.notifyIcon.BalloonTipText = "系統監控中... ..."; this.notifyIcon.ShowBalloonTip(2000); this.notifyIcon.Text = "系統監控中... ..."; this.notifyIcon.Icon = new System.Drawing.Icon(@"AppIcon.ico"); this.notifyIcon.Visible = true; //打開菜單項 System.Windows.Forms.MenuItem open = new System.Windows.Forms.MenuItem("Open"); open.Click += new EventHandler(Show); //退出菜單項 System.Windows.Forms.MenuItem exit = new System.Windows.Forms.MenuItem("Exit"); exit.Click += new EventHandler(Close); //關聯托盤控件 System.Windows.Forms.MenuItem[] childen = new System.Windows.Forms.MenuItem[] { open, exit }; notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(childen); this.notifyIcon.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler((o, e) => { if (e.Button == MouseButtons.Left) this.Show(o, e); }); } private void Show(object sender, EventArgs e) { this.Visibility = System.Windows.Visibility.Visible; this.ShowInTaskbar = true; this.Activate(); } private void Hide(object sender, EventArgs e) { this.ShowInTaskbar = false; this.Visibility = System.Windows.Visibility.Hidden; } private void Close(object sender, EventArgs e) { System.Windows.Application.Current.Shutdown(); } }
運行時發現,程序一定要能找到ICON,否則會報錯,並且ICON還沒包含到程序中,需要一個額外的ICON來做托盤圖標。當然這個都是能解決的:
this.notifyIcon.Icon = new System.Drawing.Icon(@"AppIcon.ico");
將以上一句替換成下面內容,意思就是讀取程序圖標,來作為托盤圖標
this.notifyIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath);
運行,搞定,這樣你的程序就不用拖着一個ICON文件當累贅了。