如何在 VC++ 中将 HICON 转换为 HBITMAP?
VC++中如何将HICON转为HBITMAP?
How to convert HICON to HBITMAP in VC++?
我知道这是一个常见问题,但我在 Google 上找到的所有解决方案都不起作用.我需要的是一个接受参数 HICON 并返回 HBITMAP 的函数.
I know this is an FAQ but all the solutions I've found on Google don't work. What I need is a function which takes a parameter HICON and returns HBITMAP.
即使图标是 24 位、16 位或 8 位,也尽可能转换为 32 位位图.
Greatest if possible to make conversion to 32-bit bitmap even the icon is 24-bit, 16-bit or 8-bit.
这是代码,不知道哪里出错了:
This is the code, I don't know where it goes wrong:
HBITMAP icon_to_bitmap(HICON Icon_Handle) {
HDC Screen_Handle = GetDC(NULL);
HDC Device_Handle = CreateCompatibleDC(Screen_Handle);
HBITMAP Bitmap_Handle =
CreateCompatibleBitmap(Device_Handle,GetSystemMetrics(SM_CXICON),
GetSystemMetrics(SM_CYICON));
HBITMAP Old_Bitmap = (HBITMAP)SelectObject(Device_Handle,Bitmap_Handle);
DrawIcon(Device_Handle, 0,0, Icon_Handle);
SelectObject(Device_Handle,Old_Bitmap);
DeleteDC(Device_Handle);
ReleaseDC(NULL,Screen_Handle);
return Bitmap_Handle;
}
推荐答案
我没有现成的代码可以共享,但我认为这很容易.您必须创建 HBITMAP,创建设备上下文,将位图选入 DC(这将使位图成为此 DC 的绘图区域).最后调用 DrawIcon() 函数在此 DC 上绘制您的图标.之后从 DC 分离位图并销毁 DC.您的位图现在应该可以使用了.
I don't have code readily available to share, but I think this is pretty easy. You have to create the HBITMAP, create a device context, select the bitmap into the DC (this will make the bitmap the drawing area for this DC). Finally call the DrawIcon() function to draw your icon on this DC. After that detach the bitmap from the DC and destroy the DC. Your bitmap now should be ready to go.
查看代码后更新:
我相信问题出在 createCompatibleBitmap 调用中.您要求与内存 DC 兼容的位图,但内存 DC 以选择到其中的 1 位/像素位图开始.尝试要求与屏幕 DC 兼容的位图.
I believe the problem is in the createCompatibleBitmap call. You are asking for a bitmap compatible with the memory DC, but memory DCs start with a 1 bit/pixel bitmap selected into them. Try asking for a bitmap compatible with the screen DC instead.
更新 2:您可能需要查看这个问题因为它似乎与您的问题有关.
Update 2: you may want to look at this question as it seems related to your problem.
相关文章