我們通常使用的桌面軟件,都可以最小化到任務通知欄,並且可以從任務通知欄再打開當前軟件,或者通過軟件的快捷方式從任務通知欄呼出。
我們可以通過下面的方式把WPF程序最小化到任務欄。由於WPF並沒有實現Notification的功能,我們需要借助於WinForm中NotifyIcon來實現,請看代碼:
using WinForms = System.Windows.Forms; private WinForms.NotifyIcon _notifyIcon; private WinForms.ContextMenu _contextMenu; private WinForms.MenuItem _openWindow; private WinForms.MenuItem _closeApp; private System.ComponentModel.IContainer _iContainer; public MainWindow() { _contextMenu = new WinForms.ContextMenu(); _openWindow = new WinForms.MenuItem() { Text = "Hiden" }; _closeApp = new WinForms.MenuItem() { Text = "Exit"}; _iContainer = new System.ComponentModel.Container(); WinForms.MenuItem[] menuItems = new WinForms.MenuItem[] { _openWindow, _closeApp }; _contextMenu.MenuItems.AddRange(menuItems); _openWindow.Click += _openWindow_Click; _closeApp.Click += _closeApp_Click; _notifyIcon = new WinForms.NotifyIcon(_iContainer); _notifyIcon.Icon = new System.Drawing.Icon("Todolist.ico"); _notifyIcon.Text = "Todolist"; _notifyIcon.Visible = true; _notifyIcon.MouseDoubleClick += _notifyIcon_MouseDoubleClick; _notifyIcon.ContextMenu = _contextMenu; }
當關閉WPF窗體時,將當前窗體隱藏即可。
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { this.Hide(); e.Cancel = true; }
這樣我們就可以實現關閉窗體時,將程序最小化到任務通知欄了。
接下來我們要通過點擊程序的快捷方式,再次呼出當前已經啟動的程序。首先在項目的根目錄新建一個類,我們命名為Program,接下來,我們右擊項目--->屬性-->將啟動對象設置為當前文件,如圖所示:
下面我們來看一下Program類:
class Program { [DllImport("user32.dll", EntryPoint = "FindWindow")] private static extern IntPtr FindWindow(string lp1, string lp2); [DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr hwnd, int nCmdShow); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam); [STAThread] static void Main() { string appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name; bool isNewInstance; using(Mutex mutex = new Mutex(true,appName,out isNewInstance)) { if (!isNewInstance) { IntPtr handle = FindWindow(null, "MainWindow"); if (handle != IntPtr.Zero) { const int SW_SHOW = 5; const int SW_RESTORE = 9; const uint WM_SHOWWINDOW = 0x0018; const int SW_PARENTOPENING = 3; ShowWindow(handle, SW_RESTORE); ShowWindow(handle, SW_SHOW); // send WM_SHOWWINDOW message to toggle the visibility flag SendMessage(handle, WM_SHOWWINDOW, IntPtr.Zero, new IntPtr(SW_PARENTOPENING)); SetForegroundWindow(handle); } return; } App app = new App(); app.MainWindow = new MainWindow(); app.MainWindow.Show(); app.Run(); } } }
這里我們借助了一些Win32的API來實現。
通過上面的代碼,我們就可以實現一個將WPF程序最小化到任務通知欄,並且可以點擊程序/軟件快捷方式從任務通知欄顯示程序的功能。
代碼下載
另外實現程序最小化到任務通知欄,可以使用:Hardcodet.Wpf.TaskbarNotification,具體實現可以參考:http://www.hardcodet.net/
感謝您的閱讀!