简体   繁体   中英

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

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.

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM