No GDI Calls between GetHdc and ReleaseHdc

HTML clipboard

This article has been excerpted from book "Graphics Programming with GDI+".

GDI+ currently has no support to raster operations. When we use R2_XOR pen operations, we use the Graphics.GetHdc() method to get the handle to the device context. During the operation when your application uses the HDC, the GDI+ should not draw anything on the Graphics object until the Graphics.ReleaseHdc method is called. Every GetHdc call must be followed by a call to ReleaseHdc on a Graphics object, as in the following snippet:

IntPtr hdc1 = g1.GetHdc();
//Do something with hdc1
g.ReleaseHdc (hdc1);

g2 = Graphics.FromImage (curBitmap);
IntPtr hdc1 = g1.GetHdc();
IntPtr hdc2 = g2.GetHdc();
BitBlt (hdc2, 0, 0,
this.ClientRectangle.Width,
this.ClientRectangle.Height,
hdcl, 0, 0, 13369376);
g2.DrawRectangle (Pens.Red, 40, 40, 200, 200);
g1.ReleaseHdc (hdcl);
g2.ReleaseHdc (hdc2);

If we make a GDI+ call after GetHdc, the system will throw an "object busy" exception. For example, in the preceding code snippet we make a DrawRectangle call after GetHdc and before ReleaseHdc. As a result we will get an exception saying, "The object is currently in use elsewhere."

Using GDI on a GDI+ Graphics Object Backed by a Bitmap

After a call to GetHdc, we can simply call a Graphics object from a bitmap that returns a new HBITMAP structure. This bitmap does not contain the original image, but rather a sentinel pattern, which allows GDI+ to tract changes to the bitmap. When ReleaseHdc is called, changes are copied back to the original image. This type of device context is not suitable for raster operations because the handle to device context is considered write-only, and raster operations require it to be read-only. This approach may also degrade the performance because creating a new bitmap and saving changes to the original bitmap operations may tie up all your resources.

Book.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all