这篇博客主要是讲述使用Win32 API编写一个系统托盘。实现的功能有:显示提示框、气泡、上下文菜单。要实现系
统托盘,主要用到的函数是Shell_NotifyIcon,用到的结构体是NOTIFYICONDATA。
当我们鼠标放在托盘图标上时,单击右键就会出现上下文菜单,我的这个有两个菜单项,Exit和Hide。点击Exit退出程
序,点击Hide将会把窗口隐藏,当单击托盘图标时就可以显示隐藏的窗口了。具体效果可以下载源文件下来自己运行
看看。主要代码如下:
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { NOTIFYICONDATA nid ; static HMENU hMenu ; POINT point ; HINSTANCE hInstance ; switch (message) { case WM_CREATE: hInstance = (HINSTANCE) GetWindowLong (hwnd, GWL_HINSTANCE) ; hMenu = LoadMenu (hInstance, TEXT("TuoPan")) ; hMenu = GetSubMenu (hMenu, 0) ; nid.cbSize = sizeof (NOTIFYICONDATA) ; nid.hWnd = hwnd ; nid.uID = IDI_ICON1 ; nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP | NIF_INFO; nid.hIcon = LoadIcon (hInstance, MAKEINTRESOURCE(IDI_ICON1)) ; nid.uCallbackMessage = WMU_NOTIFY ; //提示框内容 wcscpy_s(nid.szTip, szAppName) ; //气泡通知 wcscpy_s(nid.szInfo, szAppName); //通知的内容 wcscpy_s(nid.szInfoTitle, L":)"); //气泡的标题 nid.uTimeout = 10000; //通知滞留的时间,ms为单位 nid.dwInfoFlags = NIIF_NONE; //图标 Shell_NotifyIcon (NIM_ADD, &nid) ; return 0 ; case WM_COMMAND: switch (LOWORD(wParam)) { case IDM_EXIT: SendMessage (hwnd, WM_DESTROY, wParam, lParam) ; return 0 ; case IDM_HIDE: ShowWindow(hwnd, SW_HIDE); return 0; } return 0 ; case WMU_NOTIFY: if(lParam == WM_RBUTTONDOWN)//托盘消息中lParam接受鼠标的行为 { GetCursorPos(&point) ; SetForegroundWindow(hwnd) ; TrackPopupMenu(hMenu, TPM_RIGHTBUTTON, point.x, point.y, 0, hwnd, NULL) ; } else if(lParam == WM_LBUTTONDOWN) { ShowWindow(hwnd, SW_SHOW); } return 0 ; case WM_DESTROY: nid.uID = IDI_ICON1 ; nid.hWnd = hwnd ; Shell_NotifyIcon (NIM_DELETE, &nid) ; PostQuitMessage (0) ; return 0 ; } return DefWindowProc (hwnd, message, wParam, lParam) ; }