Search code examples
winapivisual-c++transparencygdi+gdi

How do I copy an HICON from GDI to GDI+ with transparency?


No matter what I do, I get white/black borders around the icon... what gives?!

Is it even possible to do this correctly? How do I copy an HICON to a GDI+ Bitmap with transparency?


Solution

  • I just wasted several hours on it.

    Combined with how much I'd wasted many times before, yes, it's frustrating.

    Turns out it's a problem with GDI+. A workaround is here; here's some code that might help:

    HICON hIcon = ...;
    
    ICONINFO ii; GetIconInfo(hIcon, &ii);
    BITMAP bmp; GetObject(ii.hbmColor, sizeof(bmp), &bmp);
    
    Gdiplus::Bitmap temp(ii.hbmColor, NULL);
    Gdiplus::BitmapData lockedBitmapData;
    Gdiplus::Rect rc(0, 0, temp.GetWidth(), temp.GetHeight());
    
    temp.LockBits(&rc, Gdiplus::ImageLockModeRead, temp.GetPixelFormat(), &lockedBitmapData);
    
    Gdiplus::Bitmap image(
        lockedBitmapData.Width, lockedBitmapData.Height, lockedBitmapData.Stride,
        PixelFormat32bppARGB, reinterpret_cast<BYTE *>(lockedBitmapData.Scan0));
    
    temp.UnlockBits(&lockedBitmapData);
    
    // Now 'image' has the icon, with transparency