1.调用这个函数可以实现托盘图标的处理
WINSHELLAPI BOOL WINAPI Shell_NotifyIcon(
DWORD dwMessage,
PNOTIFYICONDATA pnid
);
2. WndProc中检测消息,然后调用此函数,进行托盘处理
OnInitDialog添加 ToTray(0);
类中添加 NOTIFYICONDATA m_nfi;
void ToTray(bool blFlags);
添加消息宏 #define WM_NOTIFYICON WM_USER + 159
void CTmpDlg::ToTray(bool blFlags)
{
m_nfi.cbSize = sizeof(NOTIFYICONDATA);
m_nfi.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
m_nfi.hWnd = this->m_hWnd;
m_nfi.uCallbackMessage = WM_NOTIFYICON; //自定义的消息什么时候发送了?谁发送了?
m_nfi.uID = IDR_MAINFRAME;
m_nfi.hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); //注意!
char chTmp[] = "Client";
::strcpy(m_nfi.szTip, chTmp);
if(blFlags)
this->ShowWindow(SW_HIDE);
Shell_NotifyIcon(NIM_ADD, &m_nfi);
}
3.映射窗口过程函数
LRESULT CTmpDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
switch(message){
case WM_CLOSE: //按下关闭窗口时,最小化到系统托盘
ToTray(1);
return 0;
case WM_NOTIFYICON: //用户消息,恢复窗口界面
if(lParam == WM_LBUTTONDBLCLK){
//鼠标双击时显示主窗口
AfxGetApp()->m_pMainWnd->ShowWindow(SW_SHOW);
}else if(lParam == WM_RBUTTONDOWN){
//鼠标右键单击弹出选单
CMenu menuPopup;
menuPopup.CreatePopupMenu();
menuPopup.AppendMenu(MF_STRING, WM_DESTROY, _T("退出")); //为什么这里用WM_DESTROY了? 系统会自动发送这个消息.?
CPoint pos;
GetCursorPos(&pos);
::SetForegroundWindow(this->m_hWnd);//把主窗口提到前台去(点击别的地方时,弹出菜单才会自动消息)
menuPopup.TrackPopupMenu(TPM_LEFTALIGN | TPM_RETURNCMD, pos.x ,pos.y, this); //这里可以用参数选择是否返回选择项ID
menuPopup.DestroyMenu();
}
break;
case WM_DESTROY:
Shell_NotifyIcon(NIM_DELETE, &m_nfi);
default:
break;
}
return CDialog::WindowProc(message, wParam, lParam);
}