Search code examples
c++winformsgdi

GDI Object leak on System.Drawing.Bitmap.GetHicon()


I've seen similar questions but none satisfies my scenario.

I am fixing a GDI Objects leak on a C++ Windows Form Application.

This is the Exception it throws:

A generic error occurred in GDI+. at System.Drawing.Bitmap.GetHicon()

This is the GetHicon call at the line where the crash happens:

this->notifyIcon1->Icon=Icon->FromHandle(((Bitmap^)imgsApp->Images[0])->GetHicon());

After doing some reading here, and on https://learn.microsoft.com/en-us/dotnet/api/system.drawing.icon.fromhandle?view=net-5.0, I see I need to call DestroyIcon() in order to release the Icon Handle (not sure if the wording is correct here), but I am having trouble doing this not being familiar with Windows Form.


Solution

  • Try this:

    IntPtr iconHandle = ((Bitmap^)imgsApp->Images[0])->GetHicon();
    Icon ^newIcon = Icon::FromHandle(iconHandle);
    this->notifyIcon1->Icon = (Icon^) newIcon->Clone();
    newIcon->Dispose();
    DestroyIcon((HICON)iconHandle.ToPointer());
    

    Per Icon.FromHandle: should I Dispose it, or call DestroyIcon?:

    Conclusion: After Icon.FromHandle, the field ownHandle is false, and thus Dispose / FromHandle won't call DestroyIcon

    Therefore: if you create an Icon using Icon.FromHandle you'll have to Dispose() the Icon as well as call DestroyIcon, just as the remarks section says