简体   繁体   English

如何使用Win32 API C ++在系统任务栏图标中显示文本-第2部分

[英]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? 我有一个与此类似的问题, 如何使用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. 我得到一个小的4x16白色图像作为系统图标,而不是文本,我不明白为什么。

I'm not using MFC/.NET just win32 api. 我不使用MFC / .NET,仅使用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 : 我目前没有安装Windows,所以我无法检查它是否可以更好地工作,但是我发现了潜在的问题-从CreateIconIndirect函数的 MSDN文档中:

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 ); 我认为DeleteDC ( hdc ); is not needed here as you used GetDC() . 因为您使用了GetDC()所以这里不需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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