2.VC设置对话框程序最小化托盘效果
1.头文件添加如下内容:
BOOL m_bTray; //托盘标记;初始元为FALSE BOOL SetTray(BOOL bTray); //设置托盘效果 afx_msg LRESULT OnTrayCallBackMsg(WPARAM wp, LPARAM lp); //托盘处理函数 //额外还要自定义一个消息 #define WM_TRAY_MSG WM_USER+1000
2.cpp文件添加:
//消息绑定 ON_MESSAGE(WM_TRAY_MSG, &xxxDlg::OnTrayCallBackMsg) //可在构造函数或OnInitDialog中初始化 m_bTray = FALSE; BOOL xxxDlg::SetTray(BOOL bTray) { BOOL bRet = FALSE; NOTIFYICONDATA tnd; tnd.cbSize = sizeof(NOTIFYICONDATA); tnd.hWnd = m_hWnd; tnd.uID = IDR_MAINFRAME; if (bTray) { tnd.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; tnd.uCallbackMessage = WM_TRAY_MSG; tnd.hIcon = LoadIcon(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME)); _tcscpy_s(tnd.szTip, sizeof(tnd.szTip), _T("Tray Test.")); //最小化托盘时鼠标移到图标时的提示语 bRet = Shell_NotifyIcon(NIM_ADD, &tnd); } else { bRet = Shell_NotifyIcon(NIM_DELETE, &tnd); } return bRet; } //响应函数处理 LRESULT xxxDlg::OnTrayCallBackMsg(WPARAM wparam, LPARAM lparam) { switch(lparam) { case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: ShowWindow(SW_RESTORE); break; case WM_RBUTTONDOWN: //右键弹出菜单 { CMenu *pMenu = NULL; CPoint pt; pMenu = m_trayPopupMenu.GetSubMenu(0); GetCursorPos(&pt); pMenu->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, pt.x, pt.y, this); break; } default: break; } return 0; }
3.上面涉及到弹出菜单, m_trayPopupMenu未定义,添加如下定义及内容:
//资源文件添加Menu,如 IDR_MENU1
显示主程序 --> ID_SHOW_MENU
退出 --> ID_EXIT_MENU
//.h添加
CMenu m_trayPopupMenu;
afx_msg void OnShowMenu();
afx_msg void OnExitMenu();
//.cpp
ON_COMMAND(ID_SHOW_MENU, &xxxDlg::OnShowMenu)
ON_COMMAND(ID_EXIT_MENU, &xxxDlg::OnExitMenu)
void xxxDlg::OnShowMenu()
{
ShowWindow(SW_RESTORE);
}
void xxxDlg::OnExitMenu()
{
SendMessage(WM_CLOSE, 0, 0);
}
//OnInitDialog中加载菜单栏
m_trayPopupMenu.LoadMenu(IDR_MENU1);
//修改 ON_WM_SYSCOMMAND() 对应的 OnSysCommand 函数,对 最小化时启动托盘 的支持
if (nID == SC_MINIMIZE)
{
ShowWindow(SW_HIDE);
if (!m_bTray)
{
SetTray(TRUE);
m_hTray = FALSE:
}
}