以编程方式更改任务栏图标(Win32, c++)

Changing taskbar icon programmatically (Win32,C++)

本文关键字:Win32 c++ 图标 编程 方式更 任务栏      更新时间:2023-10-16

我有一个c++ win32程序,我想在运行时编辑任务栏图标以显示有关程序的警报等,但是我对win32 api不太有经验,而且我在网上找不到任何东西。我找到的最接近的是http://www.windows-tech.info/17/52a5bfc45dac0ade.php,它告诉我们如何在运行时将图标从光盘上加载并更改它。

我想做他们在这个问题上所做的:在python中使用win32在内存中创建一个图标,但在c++中没有外部库。

我想做他们在这个问题上所做的:在python中使用win32在内存中创建一个图标,但在c++中没有外部库

由于接受的答案使用wxWidgets库,该库只是Win32 API的包装,因此该解决方案翻译得非常好。

你所需要做的就是使用CreateCompatibleBitmap函数在内存中创建一个位图。然后,您可以使用标准GDI绘图功能在该位图中绘图。最后,使用CreateIconIndirect函数创建图标。

最困难的部分是跟踪你的资源,并确保你在完成时释放它们,以防止内存泄漏。如果它全部封装在一个库中,使用RAII来确保对象被正确释放,那就更好了,但是如果你用c++编写C代码,它看起来像这样:

HICON CreateSolidColorIcon(COLORREF iconColor, int width, int height)
{
    // Obtain a handle to the screen device context.
    HDC hdcScreen = GetDC(NULL);
    // Create a memory device context, which we will draw into.
    HDC hdcMem = CreateCompatibleDC(hdcScreen);
    // Create the bitmap, and select it into the device context for drawing.
    HBITMAP hbmp = CreateCompatibleBitmap(hdcScreen, width, height);    
    HBITMAP hbmpOld = (HBITMAP)SelectObject(hdcMem, hbmp);
    // Draw your icon.
    // 
    // For this simple example, we're just drawing a solid color rectangle
    // in the specified color with the specified dimensions.
    HPEN hpen        = CreatePen(PS_SOLID, 1, iconColor);
    HPEN hpenOld     = (HPEN)SelectObject(hdcMem, hpen);
    HBRUSH hbrush    = CreateSolidBrush(iconColor);
    HBRUSH hbrushOld = (HBRUSH)SelectObject(hdcMem, hbrush);
    Rectangle(hdcMem, 0, 0, width, height);
    SelectObject(hdcMem, hbrushOld);
    SelectObject(hdcMem, hpenOld);
    DeleteObject(hbrush);
    DeleteObject(hpen);
    // Create an icon from the bitmap.
    // 
    // Icons require masks to indicate transparent and opaque areas. Since this
    // simple example has no transparent areas, we use a fully opaque mask.
    HBITMAP hbmpMask = CreateCompatibleBitmap(hdcScreen, width, height);
    ICONINFO ii;
    ii.fIcon = TRUE;
    ii.hbmMask = hbmpMask;
    ii.hbmColor = hbmp;
    HICON hIcon = CreateIconIndirect(&ii);
    DeleteObject(hbmpMask);
    // Clean-up.
    SelectObject(hdcMem, hbmpOld);
    DeleteObject(hbmp);
    DeleteDC(hdcMem);
    ReleaseDC(NULL, hdcScreen);
    // Return the icon.
    return hIcon;
}

添加错误检查和代码以在位图上绘制有趣的东西留给读者作为练习。

正如我在上面的评论中所说,一旦你创建了图标,你可以通过发送WM_SETICON消息并传递HICON作为LPARAM来设置窗口的图标:

SendMessage(hWnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon);

你也可以指定ICON_SMALL来设置窗口的小图标。如果您只设置了一个大图标,它将被缩小,以自动创建小图标。但是,如果您只设置了小图标,窗口将继续使用默认图标作为其大图标。大图标通常的尺寸为32x32,而小图标通常的尺寸为16x16。然而,这是不能保证的,所以不要硬编码这些值。如果需要确定,可以使用SM_CXICONSM_CYICON调用GetSystemMetrics函数来检索大图标的宽度和高度,或者调用SM_CXSMICONSM_CYSMICON来检索小图标的宽度和高度。

一个相当好的教程在Windows中使用GDI绘图在这里可用。如果这是你第一次这样做,并且没有GDI的经验,我建议你仔细阅读。