The Problem At my place of employment, I have been tasked with cleaning up code and fixing bugs on some software that we are trying to pass around as a beta. The application involves a large amount of GDI+ through C#’s System.Drawing namespace. One of the things we were doing with this was to change the cursor whenever the user was placing an image on the form. This worked pretty well, unless the user were to rapidly place images, at which point a generic error (thanks for the helpful description, Microsoft) would occur in GDI+ in native code where debugging couldn’t reach. I also noticed via task manager that every time an image was placed, the application used three more GDI objects, and didn’t get rid of the old ones. This prompted me to look around on the internet for the cause. The Solution I found the MSDN page for GetHBitmap() . Under the “Remarks” section, the documentation explicitly states that you have to explicitly call GDIDeleteObject in order to dispose of the resources. Now, both GetHBitmap() and GetHIcon() return IntPtr objects. I figured I would give the DeleteIcon function a try to see if it solved the problem of generic GDI+ errors as well as the increasing number of GDI+ objects. It worked well and both problems were fixed. I’m not sure if this has been addressed in newer versions of .Net or not, but it’s something to keep in mind. Microsoft should probably update their documentation. The usage is similar to the following:
[DllImport ("user32.dll", EntryPoint = "DeleteIcon"] public static extern bool DeleteIcon(IntPtr iconHandle); //then the cursor code IntPtr iconHandle = bitmap.GetHIcon(); this.Cursor = new Cursor(iconHandle); //use the cursor //reset the cursor and delete the pointer. this.Cursor = defaultCursor; DeleteIcon(iconHandle);
Hope that helps someone out there.