对话框头文件XXXDlg.h:
1.添加成员变量NOTIFYICONDATA m_nid;
2.添加tray消息响应函数的声明
afx_msg LRESULT OnTrayNotify(WPARAM wParam, LPARAM lParam);
对话框实现文件XXXDlg.cpp:
1.定义tray消息 #define UM_TRAYNOTIFY WM_USER + 11
2.CXXXDlg的构造函数添加
memset(&m_nid, 0, sizeof(m_nid)); // Initialize NOTIFYICONDATA struct m_nid.cbSize = sizeof(m_nid); m_nid.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE;
3.CXXXDlg的析构函数添加
m_nid.hIcon = NULL; Shell_NotifyIcon(NIM_DELETE, &m_nid);
4.添加消息映射:
BEGIN_MESSAGE_MAP(CMFC2Dlg, CDialog) //... ON_MESSAGE(UM_TRAYNOTIFY, &CMFC2Dlg::OnTrayNotify) //... END_MESSAGE_MAP()
5.OnInitDialog函数添加:
m_nid.hWnd = GetSafeHwnd(); m_nid.uCallbackMessage = UM_TRAYNOTIFY;
// Set tray icon and tooltip m_nid.hIcon = m_hIcon;
// Set tray notification tip information CString strToolTip = _T("托盘程序"); _tcsncpy_s(m_nid.szTip, strToolTip, strToolTip.GetLength()); Shell_NotifyIcon(NIM_ADD, &m_nid);
6.OnTrayNotify函数的实现: LRESULT CXXXDlg::OnTrayNotify(WPARAM wParam, LPARAM lParam) { UINT uMsg = (UINT)lParam;
switch(uMsg) { case WM_RBUTTONUP: { //右键处理 CMenu menuTray; CPoint point; int id; GetCursorPos(&point); menuTray.LoadMenu(IDR_MENU_TRAY); id = menuTray.GetSubMenu(0)->TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN|TPM_RIGHTBUTTON, point.x, point.y, this); #if 0 CString strInfo; strInfo.Format(L"menuid %d", id); LPCTSTR strtmp; strtmp = strInfo.GetBuffer(0); MessageBox(strtmp, L"test"); #endif switch(id){ case IDR_TRAY_EXIT: OnOK(); break; case IDR_TRAY_RESTORE:
//窗口前端显示 SetForegroundWindow(); ShowWindow(SW_SHOWNORMAL); break; default: break; } break; } case WM_LBUTTONDBLCLK: SetForegroundWindow(); ShowWindow(SW_SHOWNORMAL); break; default: break; } return 0; }
7.添加WM_SIZE消息处理:
void CMFC2Dlg::OnSize(UINT nType, int cx, int cy) { CDialog::OnSize(nType, cx, cy);
if(nType == SIZE_MINIMIZED){ ShowWindow(SW_HIDE); } } 8.菜单。
添加菜单资源 , 比如IDR_MENU_TRAY.
定义一个子菜单Tray,有若干个菜单项,比如“恢复窗口”, ID是IDR_TRAY_RESTORE,“退出”, ID是IDR_TRAY_EXIT。
在OnTrayNotify函数中捕获右击消息,弹出菜单,参考第6步。
至此,添加托盘的功能基本完成。