MFC对话框程序中创建托盘图标的方法示例
1.在对话框类头文件中声名变量和函数。
1 2 3 4 5 6 7 8 9 10 11 12 13
| class CXXDlg{ private: NOTIFYICONDATA m_notifyIconData{ 0 }; public: BOOL InitNotifyIcon(); BOOL ShowNotifyIcon(BOOL bShow); afx_msg LRESULT NotifyIconCallBack(WPARAM wParam, LPARAM lParam); };
|
2.在cpp文件中定义函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| BOOL CXXDlg::InitNotifyIcon() { m_notifyIconData.cbSize = sizeof(m_notifyIconData); m_notifyIconData.uID = IDR_MAINFRAME; m_notifyIconData.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP; m_notifyIconData.hIcon = LoadIcon(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME)); m_notifyIconData.uCallbackMessage = WM_NOTIFY_MESSAGE; lstrcpy(m_notifyIconData.szTip, _T("XX")); m_notifyIconData.hWnd = m_hWnd; return 0; }
BOOL CXXDlg::ShowNotifyIcon(BOOL bShow) { BOOL bResult = FALSE; if (bShow) { bResult = Shell_NotifyIcon(NIM_ADD, &m_notifyIconData); } else { bResult = Shell_NotifyIcon(NIM_DELETE, &m_notifyIconData); } return bResult; }
LRESULT CXXDlg::NotifyIconCallBack(WPARAM wParam, LPARAM lParam) { UINT uID{ wParam }; UINT uMouseMsg{ (UINT)lParam };
switch (uMouseMsg) { case WM_RBUTTONUP: { NotifyIconMesgRestore(0, 0); } break; case WM_LBUTTONUP: { NotifyIconMesgRestore(0, 0); } break; default: { } break; } return LRESULT(); }
LRESULT CXXDlg::NotifyIconMesgRestore(WPARAM wParam, LPARAM lParam) { ShowWindow(SW_SHOWNORMAL); ::SetWindowPos(m_hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE); ShowNotifyIcon(FALSE); return LRESULT(); }
|
3.定义WM_NOTIFY_MESSAGE并在消息映射表中增加映射
1 2 3 4 5 6 7 8 9 10 11 12
| #define WM_NOTIFY_MESSAGE WM_USER + 101
BEGIN_MESSAGE_MAP(CXXDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_WM_SIZE() ON_WM_DESTROY() ON_MESSAGE(WM_NOTIFY_MESSAGE, NotifyIconCallBack) END_MESSAGE_MAP()
|
4.增加Onsize并在OnSize中增加最小化时创建托盘图标和隐藏窗口的代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| void CXXDlg::OnSize(UINT nType, int cx, int cy) { CDialogEx::OnSize(nType, cx, cy);
if (SIZE_MINIMIZED == nType) { ShowNotifyIcon(TRUE); ShowWindow(SW_HIDE); } }
|
到这里对话框程序已经可以最小化到托盘了。
5.参考
Shell_NotifyIcon https://docs.microsoft.com/en-us/previous-versions/aa922175(v=msdn.10)
)