我想做他们在这个问题中所做的事情:在python中使用win32在内存中创建一个图标 https://stackoverflow.com/questions/211046/create-an-icon-in-memory-with-win32-in-python但在 C++ 中并且没有外部库
由于接受的答案使用了 wxWidgets 库,它只是 Win32 API 的包装器,因此该解决方案转换得非常好。
您需要做的就是使用以下命令在内存中创建一个位图CreateCompatibleBitmap http://msdn.microsoft.com/en-us/library/windows/desktop/dd183488.aspx功能。然后您可以使用标准 GDI 绘图函数绘制该位图。最后,您使用以下命令创建图标CreateIconIndirect http://msdn.microsoft.com/en-us/library/windows/desktop/ms648062.aspx功能。
最困难的部分是跟踪您的资源并确保在完成后释放它们以防止内存泄漏。如果将其全部封装在一个使用 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 message http://msdn.microsoft.com/en-us/library/windows/desktop/ms632643.aspx并通过HICON
as the LPARAM
:
SendMessage(hWnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
您还可以指定ICON_SMALL
以便设置窗口的小图标。如果您只设置了大图标,它会自动缩小以创建小图标。但是,如果您仅设置小图标,窗口将继续使用默认图标作为其大图标。大图标通常尺寸为 32x32,而小图标通常尺寸为 16x16。但是,这并不能得到保证,因此不要对这些值进行硬编码。如果您需要确定它们,请致电GetSystemMetrics http://msdn.microsoft.com/en-us/library/windows/desktop/ms724385.aspx功能与SM_CXICON
and SM_CYICON
检索大图标的宽度和高度,或者SM_CXSMICON
and SM_CYSMICON
检索小图标的宽度和高度。
提供了关于使用 GDI 在 Windows 中绘图的相当好的教程here http://www.codeproject.com/Articles/224754/Guide-to-Win32-Memory-DC。如果这是您第一次这样做并且之前没有 GDI 经验,我建议您仔细阅读它。