Thursday, October 20, 2005

Avoid Leaking from PrinterSettings (.Net 1.1)

In .Net 1.1, it was possible for you to incur a GDI object leak when you get a Graphics instance via the PrinterSettings.CreateMeasurementGraphics() call. You would use CreateMeasurementGraphics() when you want to get printable area information in order to layout your print job relative to the current printer settings.

In order to avoid the leak, you must dispose the Graphics instance as follows:

Graphics pageGraphics = printerSettings.CreateMeasurementGraphics();
DisposeGraphicsDeletingDC(pageGraphics);

Where:

public static void DisposeGraphicsDeletingDC(Graphics graphics)
{
IntPtr hDC = graphics.GetHdc();
graphics.ReleaseHdc(hDC);
Win32GDI.DeleteDC(hDC);
graphics.Dispose();
}

Where Win32GDI.DeleteDC() is simply a wrapper around the Win32 DeleteDC() API.

I tried exercising this in Visual Studio 2005 and lo and behold, this problem is fixed!

1 Comments:

At 9:16 AM, Anonymous Dima said...

Many thanks for posting this workaround, helped me fix a bug in my component. Much appreciated!

 

Post a Comment

<< Home