How do I get the dimensions of a cursor or icon?

Raymond Chen

Given a HICON or a HCURSOR, how do you get the dimensions of the icon or cursor?

The GetIconInfo function gets you most of the way there, returning you an ICONINFO structure which gives you the mask and color bitmaps (and the hotspot, if a cursor). You can then use the GetObject function to get the attributes of the bitmap. And then here’s the tricky part: You have to massage the data a bit.

// Also works for cursors
BOOL GetIconDimensions(__in HICON hico, __out SIZE *psiz)
  BOOL fResult = GetIconInfo(hico, &ii);
  if (fResult) {
    BITMAP bm;
    fResult = GetObject(ii.hbmMask, sizeof(bm), &bm) == sizeof(bm);
    if (fResult) {
      psiz->cx = bm.bmWidth;
      psiz->cy = ii.hbmColor ? bm.bmHeight : bm.bmHeight / 2;
    if (ii.hbmMask)  DeleteObject(ii.hbmMask);
    if (ii.hbmColor) DeleteObject(ii.hbmColor);
  return fResult;

As we’ve learned over the past few days, an icon consists of two bitmaps, a mask and an image. A cursor is the same as an icon, but with a hotspot.

To get the dimensions of the icon or cursor, just take the dimensions of the color bitmap. If you have one.

If the icon/cursor is monochrome, then there is no color bitmap. As we’ve learned, in that case, the mask and image bitmaps are combined into a single double-height bitmap, and the color is reported as NULL. To get the size of the image, you therefore have to take the mask bitmap and divide its height by two.


Discussion is closed.

Feedback usabilla icon