Question

In Windows, given a handle to an icon (HICON), how do you clone it?

e.g.

HICON CloneIcon(HICON OriginalIcon)
{
    ICON clone;
    //...

    return clone;
}
Was it helpful?

Solution

Use the Win32 API function DuplicateIcon:

HICON CloneIcon(HICON OriginalIcon)
{
    return DuplicateIcon(NULL, OriginalIcon); //first parameter is unused
}

OTHER TIPS

Here's the Delphi code to clone an icon.

function CloneIcon(ico: HICON): HICON;
var
    info: ICONINFO;
    bm: BITMAP;
    cx, cy: Integer;
begin
   //Get the icon's info (e.g. its bitmap)
   GetIconInfo(ico, {var}info);

   //Get the bitmap info associated with the icon's color bitmap
   GetObject(info.hbmColor, sizeof(bm), @bm);

   //Copy the actual icon, now that we know its width and height
   Result := CopyImage(ico, IMAGE_ICON, bm.bmWidth, bm.bmHeight, 0);

   DeleteObject(info.hbmColor);
   DeleteObject(info.hbmMask);
end;

And transcoding to a C/C#-style language in my head:

HICON CloneIcon(HICON ico)
{
   ICONINFO info;

   //Get the icon's info (e.g. its bitmap)
   GetIconInfo(ico, ref info);

   //Get the bitmap info associated with the icon's color bitmap    
   BITMAP bm;
   GetObject(info.hbmColor, sizeof(bm), &bm));

   //Copy the actual icon, now that we know its width and height
   HICON result = CopyImage(ico, IMAGE_ICON, bm.bmWidth, bm.bmHeight, 0);

   DeleteObject(info.hbmColor);
   DeleteObject(info.hbmMask);

   return result;
}

Note: Any code released into public domain. No attribution required.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top