Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Win32.DestroyIcon vs. Icon.Dispose

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.

like image 260
DukeOfMarmalade Avatar asked Mar 27 '12 15:03

DukeOfMarmalade


People also ask

What does the destroy icon function do?

Thank you. Destroys an icon and frees any memory the icon occupied. A handle to the icon to be destroyed. The icon must not be in use. If the function succeeds, the return value is nonzero. If the function fails, the return value is zero.

How to destroy an icon from a form?

Me.Icon = newIcon ' You can now destroy the icon, since the form creates its ' own copy of the icon accessible through the Form.Icon property. DestroyIcon (newIcon.Handle) End Sub When using this method, you must dispose of the original icon by using the DestroyIcon method in the Windows API to ensure that the resources are released.

How to dispose of the original icon in Windows API?

DestroyIcon (newIcon.Handle) End Sub When using this method, you must dispose of the original icon by using the DestroyIcon method in the Windows API to ensure that the resources are released.

How to remove an icon from an object?

The only really decent way to deal with this is to override the behavior of Icon.FromHandle () and force the object to take ownership of the native icon handle. So that it will automatically call DestroyIcon () when you dispose it. That requires a hack, the Icon constructor that lets you do this is internal.


1 Answers

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.

like image 139
Reed Copsey Avatar answered Oct 05 '22 18:10

Reed Copsey