Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert HICON to HBITMAP in VC++?

How to convert HICON to HBITMAP in VC++?

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.

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;
}
like image 330
jondinham Avatar asked Sep 10 '11 22:09

jondinham


2 Answers

HDC hDC = GetDC(NULL);
HDC hMemDC = CreateCompatibleDC(hDC);
HBITMAP hMemBmp = CreateCompatibleBitmap(hDC, x, y);
HBITMAP hResultBmp = NULL;
HGDIOBJ hOrgBMP = SelectObject(hMemDC, hMemBmp);

DrawIconEx(hMemDC, 0, 0, hIcon, x, y, 0, NULL, DI_NORMAL);

hResultBmp = hMemBmp;
hMemBmp = NULL;

SelectObject(hMemDC, hOrgBMP);
DeleteDC(hMemDC);
ReleaseDC(NULL, hDC);
DestroyIcon(hIcon);
return hResultBmp;
like image 154
Euan Avatar answered Nov 14 '22 23:11

Euan


this code do it:

HICON hIcon = (HICON)LoadImage(instance, MAKEINTRESOURCEW(IDI_ICON), IMAGE_ICON, width, height, 0);
ICONINFO iconinfo;
GetIconInfo(hIcon, &iconinfo);
HBITMAP hBitmap = iconinfo.hbmColor;

and this is the code in the *.rc file:

IDI_ICON ICON "example.ico"

and this is the code in the *.h file:

#define IDI_ICON 4000
like image 33
user1544067 Avatar answered Nov 14 '22 21:11

user1544067