Click here to Skip to main content
Click here to Skip to main content

Basic use of Shell_NotifyIcon in Win32

By , 15 Aug 2003
 

Introduction

Recently I was browsing CodeProject, looking for a simple example of how to manage system tray icons. Ooops sorry, I shouldn't call them tray icons as MSDN documentation so carefully points out:

"The taskbar notification area is sometimes erroneously called the tray."

In spite of this, I will insist on calling a spade a shovel and refer to the "taskbar notification area" as the "tray" and "taskbar notification area icons" as "tray icons". Anyway back to the point, why another article about tray icons?

  • I've never written a Code Project article before and this seemed pretty easy.
  • This isn't another wrapper, but simple straight forward example of Shell_NotifyIcon with a minimum amount of code.
  • I wanted an example written in pure Win32 code.
  • I wanted to address some of the common problems and questions I've seen posted in other articles on the subject.

The basics

Adding, modifying, hiding and deleting tray icons is accomplished in two steps:

  1. Initialize a NOTIFYICONDATA structure
  2. Call Shell_NotifyIcon

Initialize a NOTIFYICONDATA structure

// zero the structure - note: Some Windows funtions
// require this but I can't be bothered to remember
// which ones do and which ones don't.


    NOTIFYICONDATA niData; 
    ZeroMemory(&niData,sizeof(NOTIFYICONDATA));


// get Shell32 version number and set the size of the
// structure note: the MSDN documentation about this is
// a little dubious(see bolow) and I'm not at all sure
// if the code bellow is correct


    ULONGLONG ullVersion =
        GetDllVersion(_T("Shell32.dll"));

    if(ullVersion >= MAKEDLLVERULL(6,0,0,0))
        niData.cbSize = sizeof(NOTIFYICONDATA);

    else if(ullVersion >= MAKEDLLVERULL(5,0,0,0))
        niData.cbSize = NOTIFYICONDATA_V2_SIZE;

    else niData.cbSize = NOTIFYICONDATA_V1_SIZE;


// the ID number can be any UINT you choose and will
// be used to identify your icon in later calls to
// Shell_NotifyIcon


    niData.uID = MY_TRAY_ICON_ID;


// state which structure members are valid
// here you can also choose the style of tooltip
// window if any - specifying a balloon window:
// NIF_INFO is a little more complicated 


    niData.uFlags = NIF_ICON|NIF_MESSAGE|NIF_TIP;


// load the icon note: you should destroy the icon
// after the call to Shell_NotifyIcon


    niData.hIcon =
        (HICON)LoadImage( hInstance,
            MAKEINTRESOURCE(IDI_MY_ICON),
            IMAGE_ICON,
            GetSystemMetrics(SM_CXSMICON),
            GetSystemMetrics(SM_CYSMICON),
            LR_DEFAULTCOLOR);


// set the window you want to recieve event messages


    niData.hWnd = hWnd;


// set the message to send
// note: the message value should be in the
// range of WM_APP through 0xBFFF


    niData.uCallbackMessage = MY_TRAY_ICON_MESSAGE;

Call Shell_NotifyIcon

// NIM_ADD adds a new tray icon
    Shell_NotifyIcon(NIM_ADD,&niData);

Stealth dialog

I've seen more than a few posts asking how to begin a dialog app minimized to the system tray, hence the name Stealth Dialog. This can be accomplished simply by first creating a modeless dialog:

    HWND hWnd = CreateDialog( hInstance,
        MAKEINTRESOURCE(MY_DIALOG),
        NULL,
        (DLGPROC)MyDlgProc );

Then use Shell_NotifyIcon as shown above to add your icon to the tray. Do not call ShowWindow.

Menus and messages

Messages from the tray will go to the window specified by the hWnd member of the NOTIFYICONDATA struct and the message ID is specified by the uCallbackMessage member (see above). The specific message is in the LPARAM.

INT_PTR CALLBACK MyDlgProc(HWND hWnd, UINT message,
    WPARAM wParam, LPARAM lParam)
{
    switch(message)
    {
    case MY_TRAY_ICON_MESSAGE:
        switch(lParam)
        {
        case WM_LBUTTONDBLCLK:
            ShowWindow(hWnd, SW_RESTORE);
            break;
        case WM_RBUTTONDOWN:
        case WM_CONTEXTMENU:
            ShowContextMenu(hWnd);
        }
        break;
    case...

If you implement a context menu, messages are received through WM_COMMAND and the menu item ID is contained in the low-order word of the WPARAM.

    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
        case MY_MENU_MSG1:
            ...
            break;
        case MY_MENU_MSG2:
        ...

Important: If you implement a context menu, it's vital that you set your window to the foreground before calling TrackPopupMenu to ensure the menu closes properly.

void ShowContextMenu(HWND hWnd)
{
    ...

    HMENU hMenu;

// create or load a menu

    ...

    SetForegroundWindow(hWnd);
    TrackPopupMenu(hMenu, ...

Cleaning up

Sometime before your app closes you should remove your tray icon by calling Shell_NotifyIcon with the NIM_DELETE flag.

    case WM_DESTROY:
        Shell_NotifyIcon(NIM_DELETE,&niData);

Notes:

The MSDN documentation says about the cbSize member of the NOTIFYICONDATA structure:

"You can keep your application compatible with all Shell32.dll versions while still using the current header files by setting the size of the NOTIFYICONDATA structure appropriately. Before initializing the structure, use the DllGetVersion function to determine which Shell32.dll version is installed on the system. If it is version 5.0 or greater, initialize the cbSize member with:

nid.cbSize = sizeof(NOTIFYICONDATA);

Setting cbSize to this value enables all the version 5.0 and 6.0 enhancements. For earlier versions, the size of the pre-6.0 structure is given by the NOTIFYICONDATA_V2_SIZE constant and the pre-5.0 structure is given by the NOTIFYICONDATA_V1_SIZE constant. Initialize the cbSize member with:

nid.cbSize = NOTIFYICONDATA_V2_SIZE;

Using this value for cbSize enables your application to use NOTIFYICONDATA with earlier Shell32.dll versions, although without the version 6.0 enhancements:"

Now maybe it's my neighbors Turkish tobacco or maybe I'm just not catching on here, but there seems to be an overlapping conflict between "5.0 or greater" and "pre-6.0".

Anyway, if anybody can shed any light on this or anything else they care to shed light on, please shed.

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

About the Author

Abraxas23
China China
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralRe: Shell_NotifyIcon sometimes fails at startupmemberrharting1 Aug '05 - 7:32 
I've had this problem as well. The problem I see happens when you wait too long to log into Windows. My app starts up automatically, and it starts before the log in. If I wait 5 minutes before hitting CTRL-ALT-DEL to put in my password, I will see the problem very repeatably. I assume this is because the "Tray" doesn't exist yet when the app calls Shell_NotifyIcon, but I don't know. Is there a way to tell if Shell32 is intialized and ready to go?
 
Thanks, nice article!
 
Thank You
General[ELP] hide the icon of another process than the minesussNewMAn29118564512 May '05 - 20:24 
First, excuse my poor english (it's not my native language, I'm french).
Then, how can I hide icons of other programms in the systray ? Is It possible?
 
Thanks
GeneralRe: [ELP] hide the icon of another process than the minememberAbraxas2319 May '05 - 5:19 
In order to do this you would have to obtain the window handle of the program and the id number used to add the icon. There are various ways you might obtain the window handle and this would have to be done every time Windows starts. Obtaining id would probably have to be done by brute force but once obtained shouldn't change allowing you to hard code it into your app.
General[ELP] hide the icon of another process than the minesussNewMAn291185645646512 May '05 - 20:23 
First, excuse my poor english (it's not my native language, I'm french).
Then, how can I hide icons of other programms in the systray ? Is It possible?
 
Thanks
GeneralGet existing iconssussAnonymous24 Feb '05 - 14:08 
I've looked everywhere but I can't find a function to get information about other icons in the tray. I even tried using Shell_NotifyIcon with NIM_SETFOCUS, passing it the hWnd of every open window, but it just returns true every time.
GeneralRe: Get existing iconssussAnonymous24 Feb '05 - 14:11 
[continued because the stupid thing submitted my post when I tried to add a smilie <_<]
There must be some way to get existing icon info? I've looked at the windows' styles and extended styles but there's nothing that signifies whether the window has an icon or not.
QuestionHow to keep icon active on WinXP?memberdlanders23 Dec '04 - 6:38 
Does anyone know if there is an official mechanism (or have unofficial ideas;)) to keep a tray icon active so that Windows XP does not "hide" the inactive icon? I assume that by updating the icon periodically, I can keep it "active", but that seems inefficient. Frown | :(

 
Thanks,
Dave
GeneralGetDllVersion()sussAnonymous18 Dec '04 - 7:38 
Do you realize that the GetDllVersion() function is a part of the Windows CE API?
 
It would be nice if you could write a bit about how you imported it to WinNT enviorments such as Win2K/XP like another unanswered thread was about. Its seems you avoid this subject, maybe you have realized that it renders your entire article useless.
 
Best of luck to you and please try again.
GeneralRe: GetDllVersion()memberte_mike26 Dec '04 - 15:40 
I managed with VS 2003 to compile this code and run it fine with GetDllVerion().
 
I also read in MSDN that you can use GetDllVersion() to check what features you can use.
 
This MSDN article on GetDllVersion() seems to be WinNT environment code:
http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q193573
 
You can actually comment out that entire section and just use:
 
niData.cbSize = sizeof(NOTIFYICONDATA);
 
I actually did that at first to make the code even simpler for a friend to learn from.
GeneralRe: GetDllVersion()memberAbraxas2319 May '05 - 5:40 
The GetDllVersion() code I am using in this sample is a direct copy and paste from MSDN and as the previous post points out not necessary in most cases. The subject of determining system versions is amply covered in other articles and not really integral to the process of adding a tray icon. I think I will just update the article and remove it altogether.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 16 Aug 2003
Article Copyright 2003 by Abraxas23
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid