Click here to Skip to main content
15,885,985 members
Articles / Programming Languages / C++

CTrayIcon - System Tray Icon Wrapper

Rate me:
Please Sign up or sign in to vote.
3.17/5 (14 votes)
6 Jun 20078 min read 175.1K   5K   47  
An article exhibiting a wrapper class for System Taskbar icon.
#include "stdafx.h"

#include "TrayIcon.h"

CTrayIcon::CTrayIcon(HWND hWnd, UINT uIconID, HICON hIcon, LPSTR lpToolTip, MouseMsgHandlerPtr *pMouseMsgHandler, int nHandlers)
{
	SetTrayIcon(hWnd, uIconID, hIcon, lpToolTip);

	SetMouseMsgHandler(pMouseMsgHandler, nHandlers);
}

CTrayIcon::~CTrayIcon()
{
	DeleteIcon();

	delete m_pMouseMsgHandler;
}

void CTrayIcon::SetTrayIcon(HWND hWnd, UINT uIconID, HICON hIcon, LPSTR lpToolTip)
{
	m_hWnd = hWnd;
	
	m_uIconID = uIconID;
	
	m_hIcon = hIcon;
	
	m_lpToolTip = lpToolTip;	
}

void CTrayIcon::SetMouseMsgHandler(MouseMsgHandlerPtr *pMouseMsgHandler, int nHandlers)
{
	m_pMouseMsgHandler = pMouseMsgHandler;

	m_nHandlers = nHandlers;
}

LRESULT CTrayIcon::OnTaskBarCreated(WPARAM wParam, LPARAM lParam)
{
	VERIFY(AddIcon());
    return 0;
}

void CTrayIcon::OnNotifyIcon(WPARAM wParam, LPARAM lParam)
{
	UINT uID; 
    UINT uMouseMsg; 
 
    uID = (UINT) wParam; 
    uMouseMsg = (UINT) lParam; 
 
	for(int i=0; i<m_nHandlers; i++)
		if (uMouseMsg == m_pMouseMsgHandler[i]->GetMouseMsgID() ) 
			if(uID == m_uIconID)
				m_pMouseMsgHandler[i]->MouseMsgHandler();	
}

BOOL CTrayIcon::AddIcon()
{
	BOOL res; 
    NOTIFYICONDATA tnid; 
 
    tnid.cbSize = sizeof(NOTIFYICONDATA); 
    tnid.hWnd = m_hWnd; 
    tnid.uID = m_uIconID; 
    tnid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; 
    tnid.uCallbackMessage = WM_TI_NOTIFYICON; 
    tnid.hIcon = m_hIcon; 
    if (m_lpToolTip) 
        lstrcpyn(tnid.szTip, m_lpToolTip, sizeof(tnid.szTip)); 
    else 
        tnid.szTip[0] = '\0'; 
 
    res = Shell_NotifyIcon(NIM_ADD, &tnid); 
 
    if (m_hIcon) 
        DestroyIcon(m_hIcon); 
 
    return res; 
}

BOOL CTrayIcon::DeleteIcon()
{
	BOOL res; 
    NOTIFYICONDATA tnid; 
 
    tnid.cbSize = sizeof(NOTIFYICONDATA); 
    tnid.hWnd = m_hWnd; 
    tnid.uID = m_uIconID; 
         
    res = Shell_NotifyIcon(NIM_DELETE, &tnid); 
    return res; 
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Pakistan Pakistan
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions