對話框頭文件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步。
至此,添加托盤的功能基本完成。