6

I have this line of code:

System.Drawing.Icon icon = System.Drawing.Icon.FromHandle(shinfo.hIcon);

A few lines later, after icon is used I have the line:

Win32.DestroyIcon(shinfo.hIcon);

However when running a static analysis on my code it says there is a potential for Resource_Leak from icon. I am wondering will it make any difference if I call the dispose method:

icon.Dispose();

rather than the Win32.DestroyIcon() that is being used right now. Is there any difference between them? I am just maintaining this code so I am not sure if there was any special intnetion by the original developer to use Win32.DestroyIcon.

DukeOfMarmalade
  • 2,680
  • 10
  • 41
  • 70
  • Duplicate of [Icon.FromHandle: should I Dispose it, or call DestroyIcon?](https://stackoverflow.com/questions/30979653/icon-fromhandle-should-i-dispose-it-or-call-destroyicon) – Herohtar Dec 02 '19 at 21:13

2 Answers2

7

The static analysis is triggering because you aren't disposing the "IDisposable resource".

I would recommend sticking to the managed version throughout, and using icon.Dispose(). This will (internally) take care of calling DestroyIcon for you, but stick to the pure managed API throughout.

Win32.DestroyIcon is really intended more for use with icons you're receiving as an IntPtr, not for use with an Icon instance that is managed by the framework entirely.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 4
    Actually, `icon.Dispose()` only destroys the icon if the (private) boolean `ownHandle` is true, and that depends on the way the the managed icon object was constructed. Specifically, [`Icon.FromHandle(..)` sets that boolean to false](https://referencesource.microsoft.com/#System.Drawing/commonui/System/Drawing/Icon.cs,3a4e2c70109d46bc) and so [`Icon.Dispose()` does nothing at all](https://referencesource.microsoft.com/#System.Drawing/commonui/System/Drawing/Icon.cs,8d050d7603efcc48). – JBSnorro Jan 14 '18 at 22:15
  • 3
    This answer is wrong. When using `Icon.FromHandle()`, calling `Dispose()` on the resulting icon **will not** call `DestroyIcon` and you will have a resource leak. – Herohtar Dec 02 '19 at 20:14
3

I have had NO END of grief in this area - I've been trying to animate a form's icon (and consequently the one in the task bar) without it leaking resources.

When I disposed of the icon (as suggested on MSDN) resources leaked, when I used "DestroyIcon" all subsequent updates failed. This code below shows everything in the correct order.

API Declaration:

[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = CharSet.Auto)]
extern static bool DestroyIcon(IntPtr handle);

FINALLY the solution:

IntPtr iconHandle = dynamicBitmap.GetHicon();
Icon tempManagedRes = Icon.FromHandle(iconHandle);
this.Icon = (Icon)tempManagedRes.Clone();
tempManagedRes.Dispose();
DestroyIcon(iconHandle);

Also posted in this question: Icon.FromHandle: should I Dispose it, or call DestroyIcon?

Community
  • 1
  • 1
Dave
  • 3,093
  • 35
  • 32