How to display text in system tray icon with win32 api C++



I have a question similar to this, http://stackoverflow.com/questions/457050/how-to-display-text-in-system-tray-icon-with-win32-api

I tried his solution but it's not working for me. I get a small 4x16 white image as the system icon instead of text and I can't understand why.

I'm not using MFC/.NET just win32 api.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
void UpdateIcon(HWND hWnd){
	NOTIFYICONDATA nid;
	nid.cbSize = sizeof(NOTIFYICONDATA);
	nid.hWnd = hWnd;
	nid.uID = 100;
	nid.hIcon = CreateSmallIcon(hWnd);
	nid.uFlags = NIF_ICON;
	Shell_NotifyIcon(NIM_MODIFY, &nid);
}

HICON CreateSmallIcon( HWND hWnd )
{
    static TCHAR *szText = TEXT ( "100" );
    HDC hdc, hdcMem;
    HBITMAP hBitmap = NULL;
    HBITMAP hOldBitMap = NULL;
    HBITMAP hBitmapMask = NULL;
    ICONINFO iconInfo;
    HFONT hFont;
    HICON hIcon;

    hdc = GetDC ( hWnd );
    hdcMem = CreateCompatibleDC ( hdc );
    hBitmap = CreateCompatibleBitmap ( hdc, 16, 16 );
    hBitmapMask = CreateCompatibleBitmap ( hdc, 16, 16 );
    ReleaseDC ( hWnd, hdc );
    hOldBitMap = (HBITMAP) SelectObject ( hdcMem, hBitmap );
    PatBlt ( hdcMem, 0, 0, 16, 16, WHITENESS );

    // Draw percentage
    hFont = CreateFont (12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    TEXT ("Arial"));
    hFont = (HFONT) SelectObject ( hdcMem, hFont );
    TextOut ( hdcMem, 0, 0, szText, lstrlen (szText) );

    SelectObject ( hdc, hOldBitMap );
    hOldBitMap = NULL;

    iconInfo.fIcon = TRUE;
    iconInfo.xHotspot = 0;
    iconInfo.yHotspot = 0;
    iconInfo.hbmMask = hBitmapMask;
    iconInfo.hbmColor = hBitmap;

    hIcon = CreateIconIndirect ( &iconInfo );

    DeleteObject ( SelectObject ( hdcMem, hFont ) );
    DeleteDC ( hdcMem );
    DeleteDC ( hdc );
    DeleteObject ( hBitmap );
    DeleteObject ( hBitmapMask );

    return hIcon;
}

I'm thinking that your 'NOTIFYICONDATA' struct should be static, this is so that the data that you modifying survives past the end of the function. Either make it static or Global.

Also you do realize that none of your data is changing yet right? It's just that we get a lot of beginners in here so I wanted to make sure you realized this.
It worked for me when I commented out line 28. You might want to use FillRect instead. Also make sure you delete the icon after you use it in UpdateIcon or else you will have a memory leak.
Topic archived. No new replies allowed.