October 5th, 2012

How do I override the default icon selection algorithm?

The usual way of loading an icon from a resource is to use the Load­Icon or Load­Image function and letting the window manager’s icon selection algorithm decide which image to use based on the images available in the icon, the desired icon size, and the current color depth. A customer wanted to override that algorithm, because the window manager uses the current display color depth to select an image, but they were obtaining the icon for printing purposes, so they wanted to get the highest-color-quality icon rather than the one that matched the screen’s color depth. How do you override the default algorithm?

You basically do the same thing the window manager does. As we saw earlier, icon resources are actually stored in multiple pieces. The thing you use to talk about icons is actually the icon directory, which in turn points to a set of images. The first step, then, is to obtain the icon directory.

HRSRC hrsrcIcon = FindResource(hResources,
                     MAKEINTRESOURCE(IDI_MY_ICON), RT_GROUP_ICON);
HGLOBAL hIcon = LoadResource(hResources, hrsrcIcon);
auto lpIcon = static_cast<GRPICONDIR *>(LockResource(hIcon));

You then take the images listed in the GRPICONDIR and apply your custom algorithm to decide which one you like best. (If you want to use the default algorithm, you can call Lookup­Icon­Id­From­Directory or Lookup­Icon­Id­From­Directory­Ex. But if you want to use the default algorithm, then just use Load­Image already!)

When you’ve found the image you like, take the nId, and that’s the resource ID for the RT_ICON.

HRSRC hrsrcImage = FindResource(hResources,
                     MAKEINTRESOURCE(nId), RT_ICON);
HGLOBAL hImage = LoadResource(hResources, hrsrcImage);
auto lpImage = static_cast<PBYTE>(LockResource(hImage));

You can then convert the icon image data into an icon by using the Create­Icon­From­Resource or Create­Icon­From­Resource­Ex function.

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.