我有一个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;
}
Run Code Online (Sandbox Code Playgroud)
添加错误检查和代码以在位图上绘制有趣的东西留给读者练习.
正如我在上面的评论中所说,一旦你创建了图标,你就可以通过向窗口发送WM_SETICON
消息并将其传递HICON
给LPARAM
:
SendMessage(hWnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
Run Code Online (Sandbox Code Playgroud)
您还可以指定ICON_SMALL
以设置窗口的小图标.如果您只设置一个大图标,它将缩小以自动创建小图标.但是,如果仅设置小图标,则窗口将继续使用默认图标作为其大图标.大图标的尺寸通常为32x32,而小图标的尺寸通常为16x16.但是,这不是保证,所以不要硬编码这些值.如果您需要确定它们,调用GetSystemMetrics
函数SM_CXICON
和SM_CYICON
检索的大图标的宽度和高度,或SM_CXSMICON
和SM_CYSMICON
检索的小图标的宽度和高度.
使用GDI在Windows中绘制一个相当好的教程,请点击这里.如果这是你第一次这样做而且之前没有GDI经验,我建议你仔细阅读.
归档时间: |
|
查看次数: |
4116 次 |
最近记录: |