stack356
stack356

Reputation: 170

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

I have a question similar to this, 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.

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;
}

Upvotes: 1

Views: 1426

Answers (2)

foudfou
foudfou

Reputation: 1076

You need to set background and possibly foreground colors:

SetTextColor( hdcMem, 0x00FF0000 ); // 0x00bbggrr, not rrggbb !!
SetBkMode( hdcMem, TRANSPARENT ); // VERY IMPORTANT

I think DeleteDC ( hdc ); is not needed here as you used GetDC().

Upvotes: 0

j_kubik
j_kubik

Reputation: 6181

I don't have windows installed currently so i cannot check if this will work better, but i found potential problem - from MSDN documentation of CreateIconIndirect function:

The application must continue to manage the original bitmaps and delete them when they are no longer necessary.

Seems like you are deleting bitmaps too soon.

Upvotes: 1

Related Questions