为CMainFrame增加如下的成员变量:
NOTIFYICONDATA m_trayIcon;
CMenu m_menuTray;
在CMainFrame的OnCreate函数末尾增加:
m_trayIcon.cbSize = sizeof(NOTIFYICONDATA);
m_trayIcon.hIcon = (HICON)LoadImage(AfxGetApp()->m_hInstance,
MAKEINTRESOURCE(IDI_TRAYICON), IMAGE_ICON, 16, 16, 0);
m_trayIcon.hWnd = m_hWnd;
m_trayIcon.uID = MAINTRAYICON;
m_trayIcon.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
m_trayIcon.uCallbackMessage = WM_TRAYICON;
strcpy(m_trayIcon.szTip, LoadResString(IDS_TOOLTIP));
Shell_NotifyIcon(NIM_ADD, &m_trayIcon);
增加消息WM_TRAYICON响应函数:
ON_MESSAGE(WM_TRAYICON,OnTrayNotify)
int CMainFrame::OnTrayNotify(WPARAM wParam, LPARAM lParam)
{
if(wParam != MAINTRAYICON)
return 0L;
if(m_menuTray.m_hMenu == NULL && !m_menuTray.LoadMenu(IDR_MAINFRAME))
return 0;
CMenu* pSubMenu = m_menuTray.GetSubMenu(0);
if (!pSubMenu)
return 0;
if (lParam == WM_RBUTTONUP)
{
::SetMenuDefaultItem(pSubMenu->m_hMenu, 0, TRUE);
CPoint pos;
GetCursorPos(&pos);
SetForegroundWindow();
pSubMenu->TrackPopupMenu(TPM_RIGHTALIGN|TPM_LEFTBUTTON
|TPM_RIGHTBUTTON, pos.x, pos.y, this, NULL);
}
else if(lParam == WM_LBUTTONDOWN)
{
ShowWindow(SW_SHOW);
SetForegroundWindow();
}
else if(lParam == WM_LBUTTONDBLCLK)
{
SendMessage(WM_COMMAND, pSubMenu->GetMenuItemID(0), 0);
}
return 1L;
}
如果同时还需要屏蔽窗口关闭按钮的话需要增加消息处理函数:
ON_WM_SYSCOMMAND()
void CMainFrame::OnSysCommand(UINT nID, LPARAM lParam)
{
if(nID == SC_CLOSE)
{
ShowWindow(SW_HIDE);
return;
}
CFrameWnd::OnSysCommand(nID, lParam);
}
在窗口的Destroy函数调用:
Shell_NotifyIcon(NIM_DELETE, &m_trayIcon);