cwinapisystem-tray

How to display text in system tray icon with win32 API?


Trying to create a small monitor application that displays current internet usage as percentage in system tray in C using win32 API.

Also wanting to use colour background or colour text based on how much is used relative to days left in month.

EDIT: To clarify I am wanting the system tray icon to be dynamic. As the percentage changes I update the system tray icon. Looking for solution that uses just plain old win32 (ie. No MFC or WTL).


Solution

  • Okay here is my win32 solution:

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