No GDI Calls between GetHdc and ReleaseHdc in VB.NET

In this article you will learn how to use No GDI Calls between GetHdc and ReleaseHdc.
  • 3149

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:

        Dim hdc1 As IntPtr = g1.GetHdc()
        'Do something with hdc1
        g.ReleaseHdc(hdc1)

        g2 = Graphics.FromImage(curBitmap)
        Dim hdc1 As IntPtr = g1.GetHdc()
        Dim hdc2 As IntPtr = g2.GetHdc()
        BitBlt(hdc2, 0, 0, Me.ClientRectangle.Width, Me.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.

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.