简介
本方法可实现在托盘栏中创建MFC程序图标,并在左键、中键或右键单击时触发相应操作(如显示菜单、显示程序主窗口等)。
代码(C++)
本例中类名为TimePresenterDlg
TimePresenterDlg.h
……
public:
class CTimePresenterDlg : public CDialogEx
{
……
public:
……
afx_msg LRESULT OnTrayNotify(WPARAM wParam, LPARAM lParam);
void ToTray();
NOTIFYICONDATA m_nid;
void OpenMenu();
……
};
……
TimePresenterDlg.cpp
……
#define UM_TRAYNOTIFY WM_USER + 1//值按实际需求确定
……
//添加响应事件
BEGIN_MESSAGE_MAP(CTimePresenterDlg, CDialogEx)
……
ON_MESSAGE(UM_TRAYNOTIFY, &CTimePresenterDlg::OnTrayNotify)
……
END_MESSAGE_MAP()
……
//添加托盘栏图标
void CTimePresenterDlg::ToTray()
{
m_nid.hWnd = GetSafeHwnd();
m_nid.uCallbackMessage = UM_TRAYNOTIFY;
m_nid.hIcon = m_hIcon;
//m_hIcon为程序图标,亦可通过
//HICON ICON = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
//来自定义图标
CString strToolTip = _T("NAME");//鼠标悬浮在托盘栏图标时显示的文字
_tcsncpy_s(m_nid.szTip, strToolTip, strToolTip.GetLength());
Shell_NotifyIcon(NIM_ADD, &m_nid);
}
……
//响应事件操作
LRESULT CTimePresenterDlg::OnTrayNotify(WPARAM wParam, LPARAM lParam)
{
UINT uMsg = (UINT)lParam;
switch (uMsg) {
case WM_LBUTTONUP://左键,本例为打开菜单,按实际需求确定
OpenMenu();
break;
case WM_RBUTTONUP://右键,本例为打开菜单,按实际需求确定
OpenMenu();
break;
case WM_MBUTTONUP://中键,本例为打开菜单,按实际需求确定
OpenMenu();
break;
default:
break;
}
return LRESULT();
}
……
//打开菜单
void CTimePresenterDlg::OpenMenu() {
CMenu menuTray;
CPoint point;
int id;
GetCursorPos(&point);
menuTray.LoadMenu(IDR_MENU_TRAY);
SetForegroundWindow();
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://退出
m_nid.hIcon = NULL;
Shell_NotifyIcon(NIM_DELETE, &m_nid);
OnOK();
break;
case IDR_MENU_ABOUT://菜单项ID,可自定义
break;
default:
break;
}
}
……
调用
//以下内容须在与上文同一cpp文件或进行适当引用后使用
//显示托盘栏图标
ToTray();
//删除托盘栏图标(退出前请调用以下内容,否则托盘栏图标无法自动消失)
Shell_NotifyIcon(NIM_DELETE, &m_nid);