.net – GDI handles in a DotNET application

countgdi+handlememory-leaksnet

My pure DotNET library runs as a plugin inside an unmanaged desktop application. I've been getting a steady (though low) stream of crash reports that seem to indicate a problem with GDI handles (fonts in error messages etc. revert to the system font, display of all sorts of controls break down, massive crash shortly after).

My Forms have few controls, but I do a lot of GDI+ drawing in User controls. What's a good way to tell how many handles I'm using, or even leaking?

Thanks,
David

Best Answer

Starting with GDIView from Ray Vega's answer, I found this tip:

[DllImport("User32")] 
extern public static int GetGuiResources(IntPtr hProcess, int uiFlags);

  public static void GetGuiResourcesGDICount()      
  { 
      //Return the count of GDI objects.          
      Console.WriteLine("GDICount"+GetGuiResources(System.Diagnostics.Process.GetCurrentProcess().Handle, 0));      
  }

  private void button1_Click(object sender, System.EventArgs e)
  {
      GetGuiResourcesGDICount();
  }

GDIView informed that it was font objects that were being leaked; I then added calls to GetGuiResources into our logging code to detect at which point the object creation was being triggered.

In our case, we had the text of a Label control being updated when its parent UserControl was hidden in a background window. This would cause GDI to leak font handles. To fix it, we changed our logic to not update the Label unless it was currently visible on screen. To determine whether it was visible, we keep a record of when the UserControl was last painted.