MFC 系统托盘
显示托盘
BOOL CMFCTrayDlg::OnInitDialog() { //... //设置托盘图标 //NOTIFYICONDATA m_NofityIcon;//.h设置为成员变量 m_NofityIcon.cbSize = sizeof(NOTIFYICONDATA); m_NofityIcon.hWnd = this->m_hWnd;//图标对应的窗口 m_NofityIcon.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;//图标属性 m_NofityIcon.uCallbackMessage = WM_NOTIFY_ICON;//对应的自定义消息 memmove(m_NofityIcon.szTip, "托盘Tip", strlen("托盘Tip")+1);//帮助信息 m_NofityIcon.uID = IDR_MAINFRAME;//图标资源ID m_NofityIcon.hIcon = m_hIcon; ::Shell_NotifyIcon(NIM_ADD, &m_NofityIcon);//添加图标到系统状态区域 return TRUE; // 除非将焦点设置到控件,否则返回 TRUE }
销毁托盘
void CMFCTrayDlg::CloseTray() { ::Shell_NotifyIcon(NIM_DELETE, &m_NofityIcon); }
自定义消息
#define WM_NOTIFY_ICON WM_USER+100 LRESULT OnTrayNotification(WPARAM wParam, LPARAM lParam); BEGIN_MESSAGE_MAP(CMFCTrayDlg, CDialog) //... //}}AFX_MSG_MAP //... ON_MESSAGE(WM_NOTIFY_ICON, OnTrayNotification) END_MESSAGE_MAP() LRESULT CMFCTrayDlg::OnTrayNotification( WPARAM wParam, LPARAM lParam ) { switch (lParam) { case WM_LBUTTONUP: { AfxGetApp()->m_pMainWnd->ShowWindow(SW_SHOWNORMAL); SetForegroundWindow(); } break; case WM_RBUTTONUP: { //弹出菜单 CPoint pos; if (GetCursorPos(&pos)) { CMenu menu; //加载菜单资源 menu.LoadMenu(IDR_MENU1); //目标子菜单是菜单资源第0列 menu.GetSubMenu(0)->TrackPopupMenu(TPM_RIGHTBUTTON, pos.x, pos.y, this); } } break; } return 1; }
响应弹出菜单消息
afx_msg void OnTrayRecovery(); afx_msg void OnTrayQuit(); BEGIN_MESSAGE_MAP(CMFCTrayDlg, CDialog) //... ON_COMMAND(ID_TRAYRECOVERY, OnTrayRecovery) ON_COMMAND(ID_TRAYQUIT, OnTrayQuit) //}}AFX_MSG_MAP //... END_MESSAGE_MAP() void CMFCTrayDlg::OnTrayRecovery() { ShowWindow(SW_SHOWNORMAL); SetForegroundWindow(); } void CMFCTrayDlg::OnTrayQuit() { CloseTray();//关闭托盘 CMFCTrayDlg::OnCancel();//退出程序 }
最小化时隐藏程序窗口
void CMFCTrayDlg::OnSysCommand(UINT nID, LPARAM lParam) { if (SC_MINIMIZE == nID) { ShowWindow(FALSE); } else { CDialog::OnSysCommand(nID, lParam); } }
当然需要添加菜单资源
posted on 2016-11-02 14:22 NoneButNow 阅读(366) 评论(0) 编辑 收藏 举报