利用Visual C++实现系统托盘程序(3)
BOOL CTrayIcon::SetIcon(UINT uID)
{
// Sets both the icon and tooltip from resource ID ,To remove the icon, call SetIcon(0)
HICON hicon=NULL;
if (uID) {
AfxLoadString(uID, m_nid.szTip, sizeof(m_nid.szTip));
hicon = AfxGetApp()->LoadIcon(uID);
}
return SetIcon(hicon, NULL);
}
BOOL CTrayIcon::SetIcon(HICON hicon, LPCSTR lpTip)
{
// Common SetIcon for all overloads.
UINT msg;
m_nid.uFlags = 0;
if (hicon) {
// Set the icon
msg = m_nid.hIcon ? NIM_MODIFY : NIM_ADD;
m_nid.hIcon = hicon; // Add or replace icon in system tray
m_nid.uFlags = NIF_ICON;
} else {
if (m_nid.hIcon==NULL) // remove icon from tray
return TRUE; // already deleted
msg = NIM_DELETE;
}
if (lpTip) // Use the tip, if any
strncpy(m_nid.szTip, lpTip, sizeof(m_nid.szTip));
if (m_nid.szTip[0])
m_nid.uFlags = NIF_TIP;
if (m_nid.uCallbackMessage && m_nid.hWnd) // Use callback if any
m_nid.uFlags = NIF_MESSAGE;
BOOL bRet = Shell_NotifyIcon(msg, &m_nid); // Do it
if (msg==NIM_DELETE !bRet)
m_nid.hIcon = NULL; // failed
return bRet;
}
LRESULT CTrayIcon::OnTrayNotification(WPARAM wID, LPARAM lEvent)
{
if (wID!=m_nid.uID (lEvent!=WM_RBUTTONUP && lEvent!=WM_LBUTTONDBLCLK))
return 0;
CMenu menu;//装载上下文菜单;
if (!menu.LoadMenu(m_nid.uID))
return 0;
CMenu* pSubMenu = menu.GetSubMenu(0);
if (!pSubMenu)
return 0;
if (lEvent==WM_RBUTTONUP) {//设置第一个菜单项为默认菜单项目
::SetMenuDefaultItem(pSubMenu->m_hMenu, 0, TRUE);
//将当前菜单作为上下文菜单;
CPoint mouse;
GetCursorPos(&mouse);
::SetForegroundWindow(m_nid.hWnd);
::TrackPopupMenu(pSubMenu->m_hMenu, 0, mouse.x, mouse.y, 0,m_nid.hWnd, NULL);
} else // double click: execute first menu item
::SendMessage(m_nid.hWnd, WM_COMMAND, pSubMenu->GetMenuItemID(0), 0);
return 1;
}
///////////////////////////////// MainFrm.h : interface of the CMainFrame class
#if !defined(AFX_MAINFRM_H__9ED70A69_C975_4F20_9D4E_B2877E3575D0__INCLUDED_)
#define AFX_MAINFRM_H__9ED70A69_C975_4F20_9D4E_B2877E3575D0__INCLUDED_
#if _MSC_VER >1000
#pragma once
#endif // _MSC_VER >1000
- 上一篇:高手必修:关于FoxMail的深入研究
- 下一篇:Visual C++编程技巧小结