创建菜单 菜单的ID为:IDR_TRAYMENU
消息:#define WM_SYSTEMTRAYICON (WM_USER+ 1000) //托盘对话框
MESSAGE_HANDLER_EX(WM_SYSTEMTRAYICON, OnSystemTrayIcon)
定义结构体:NOTIFYICONDATA m_NotifyIconData;
在对话框初始化中
OnInitDialog
{
ZeroMemory(&m_NotifyIconData, sizeofm_NotifyIconData);
InitTray();
}
退出时调用 DelTray();
void DelTray()
{
if(m_NotifyIconData.cbSize)
{
Shell_NotifyIcon(NIM_DELETE,&m_NotifyIconData);
ZeroMemory(&m_NotifyIconData, sizeofm_NotifyIconData);
}
}
ICON部分
DEFINE_ICO(IDI_BEIKESAFE, 100, "res\\XYNetGuard.ico")
//系统托盘
LRESULT OnSystemTrayIcon(UINT, WPARAM wParam,LPARAM lParam)
{
ATLASSERT(wParam == 1);
switch(lParam)
{
case WM_LBUTTONDBLCLK:
//SendMessage(WM_COMMAND,SC_RESTORE);
SetForegroundWindow(m_hWnd);
ShowWindow(SW_SHOW);
BringWindowToTop();
break;
case WM_RBUTTONUP:
{
SetForegroundWindow(m_hWnd);
CMenumenuPopup;
menuPopup.LoadMenu(IDR_TRAYMENU);
CMenuHandleMenu = menuPopup.GetSubMenu(0);;
CPointPosition;
ATLVERIFY(GetCursorPos(&Position));
Menu.TrackPopupMenu(TPM_LEFTALIGN| TPM_BOTTOMALIGN, Position.x, Position.y, m_hWnd);
}
break;
}
return 0;
}
//初始化托盘 具体代码:
void InitTray()
{
if(!m_NotifyIconData.cbSize)
{
m_NotifyIconData.cbSize= NOTIFYICONDATAA_V1_SIZE;
m_NotifyIconData.hWnd= m_hWnd;
m_NotifyIconData.uID= 1;
m_NotifyIconData.uFlags= NIF_ICON | NIF_MESSAGE | NIF_TIP;
m_NotifyIconData.uCallbackMessage= WM_SYSTEMTRAYICON;
m_NotifyIconData.hIcon= AtlLoadIconImage(IDI_BEIKESAFE, LR_DEFAULTCOLOR,GetSystemMetrics(SM_CXSMICON),GetSystemMetrics(SM_CYSMICON));
CStringsWindowText;
GetWindowText(sWindowText);
_tcscpy_s(m_NotifyIconData.szTip,sWindowText);
if(!Shell_NotifyIcon(NIM_ADD,&m_NotifyIconData))
{
SetMsgHandled(FALSE);
}
}
}