I was debugging resource leaks in my application and created a test app to test GDI object leaks. In OnPaint I create new icons and new bitmaps without disposing them. After that I check the increase of GDi objects in task manager for each of the cases. However, if I keep repainting the main window of my app, the number of GDI objects increases for icons, but there is no change for bitmaps. Is there any particular reason why icons are not getting cleaned up same way as bitmaps?
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// 1. icon increases number of GDI objects used by this app during repaint.
//var icon = Resources.TestIcon;
//e.Graphics.DrawIcon(icon, 0, 0);
// 2. bitmap doesn't seem to have any impact (only 1 GDI object)
//var image = Resources.TestImage;
//e.Graphics.DrawImage(image, 0, 0);
}
}
Test Result:
I believe that you have to take care of the icons manually. I did some searching and found that GC takes care of the bitmaps but not the icons. The forms sometimes keep their own copy of the icons (i'm not sure why). A way to dispose icons can be found here: http://dotnetfacts.blogspot.com/2008/03/things-you-must-dispose.html
[DllImport("user32.dll", CharSet = CharSet.Auto)]
extern static bool DestroyIcon(IntPtr handle);
private void GetHicon_Example(PaintEventArgs e)
{
// Create a Bitmap object from an image file.
Bitmap myBitmap = new Bitmap(@"c:\FakePhoto.jpg");
// Draw myBitmap to the screen.
e.Graphics.DrawImage(myBitmap, 0, 0);
// Get an Hicon for myBitmap.
IntPtr Hicon = myBitmap.GetHicon();
// Create a new icon from the handle.
Icon newIcon = Icon.FromHandle(Hicon);
// Set the form Icon attribute to the new icon.
this.Icon = newIcon;
// Destroy the Icon, since the form creates
// its own copy of the icon.
DestroyIcon(newIcon.Handle);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With