WPF 通知欄圖示和右鍵選單
阿新 • • 發佈:2019-02-17
WPF沒有自帶的通知欄圖示元件,需要引用Windows類庫,具體程式碼如下:
public MainWindow() { InitializeComponent(); icon(); wsl = WindowState.Minimized; } #region 通知欄 WindowState wsl; System.Windows.Forms.NotifyIcon notifyIcon = null; private void icon() { this.notifyIcon = new System.Windows.Forms.NotifyIcon(); this.notifyIcon.BalloonTipText = "ECMS 服務正在執行..."; //設定程式啟動時顯示的文字 this.notifyIcon.Text = "ECMS 服務";//最小化到托盤時,滑鼠點選時顯示的文字 this.notifyIcon.Icon = new System.Drawing.Icon("./logo_48X48.ico");//程式圖示 this.notifyIcon.Visible = true; //右鍵選單--開啟選單項 System.Windows.Forms.MenuItem open = new System.Windows.Forms.MenuItem("Open"); open.Click += new EventHandler(ShowWindow); //右鍵選單--退出選單項 System.Windows.Forms.MenuItem exit = new System.Windows.Forms.MenuItem("Exit"); exit.Click += new EventHandler(CloseWindow); //關聯托盤控制元件 System.Windows.Forms.MenuItem[] childen = new System.Windows.Forms.MenuItem[] { open, exit }; notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(childen); notifyIcon.MouseDoubleClick += OnNotifyIconDoubleClick; this.notifyIcon.ShowBalloonTip(1000); } private void OnNotifyIconDoubleClick(object sender, EventArgs e) { /* * 這一段程式碼需要解釋一下: * 視窗正常時雙擊圖示執行這段程式碼是這樣一個過程: * this.Show()-->WindowState由Normail變為Minimized-->Window_StateChanged事件執行(this.Hide())-->WindowState由Minimized變為Normal-->視窗隱藏 * 視窗隱藏時雙擊圖示執行這段程式碼是這樣一個過程: * this.Show()-->WindowState由Normail變為Minimized-->WindowState由Minimized變為Normal-->視窗顯示 */ this.Show(); this.WindowState = WindowState.Minimized; this.WindowState = WindowState.Normal; } private void Window_StateChanged(object sender, EventArgs e) { //視窗最小化時隱藏工作列圖示 if (WindowState == WindowState.Minimized) { this.Hide(); } } private void ShowWindow(object sender, EventArgs e) { this.Visibility = System.Windows.Visibility.Visible; this.ShowInTaskbar = true; this.Activate(); } private void HideWindow(object sender, EventArgs e) { this.ShowInTaskbar = false; this.Visibility = System.Windows.Visibility.Hidden; } private void CloseWindow(object sender, EventArgs e) { System.Windows.Application.Current.Shutdown(); } #endregion