October 20th, 2010

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

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)
{
  ICONINFO ii;
  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.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.