65.9K
CodeProject is changing. Read more.
Home

Copying graphics with BitBlt (.NET Style)

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (12 votes)

Dec 30, 2003

viewsIcon

200264

downloadIcon

2480

When Graphics.Clone() just won't do.

Introduction

When the basic GDI+ functions just won't do, what you want is back to API school. BitBlt quite simply makes copies of portions of the screen. This is done by accessing the Windows hDC and other low level mind numbing things.

First we most Declare the functions that are in the GDI32.DLL file so we can use them in VB.NET.

Declare Auto Function BitBlt Lib "GDI32.DLL" ( _
     ByVal hdcDest As IntPtr, _
     ByVal nXDest As Integer, _
     ByVal nYDest As Integer, _
     ByVal nWidth As Integer, _
     ByVal nHeight As Integer, _
     ByVal hdcSrc As IntPtr, _
     ByVal nXSrc As Integer, _
     ByVal nYSrc As Integer, _
     ByVal dwRop As Int32) As Boolean

Then I have created a special function that will copy the area of the screen specified by rectangleF.

Private Function copyRect(ByVal src As PictureBox, _ 
       ByVal rect As RectangleF) As Bitmap
     'Get a Graphics Object from the form
     Dim srcPic As Graphics = src.CreateGraphics
     'Create a EMPTY bitmap from that graphics
     Dim srcBmp As New Bitmap(src.Width, src.Height, srcPic)
     'Create a Graphics object in memory from that bitmap
     Dim srcMem As Graphics = Graphics.FromImage(srcBmp)

     'get the IntPtr's of the graphics
     Dim HDC1 As IntPtr = srcPic.GetHdc
     'get the IntPtr's of the graphics
     Dim HDC2 As IntPtr = srcMem.GetHdc

     'get the picture 
     BitBlt(HDC2, 0, 0, rect.Width, _ 
       rect.Height, HDC1, rect.X, rect.Y, 13369376)

     'Clone the bitmap so we can dispose this one 
     copyRect = srcBmp.Clone()

     'Clean Up 
     srcPic.ReleaseHdc(HDC1)
     srcMem.ReleaseHdc(HDC2)
     srcPic.Dispose()
     srcMem.Dispose()
     srcMem.Dispose()
End Function

Then all we need to do is call the function to return the image you want:

Dim bmp = CType(copyRect(src, _ 
    New RectangleF(0, 0, 50, src.Height)), Bitmap)    
dest.Image = bmp.CloneShorthand:

-or-

dest.Image = CType(copyRect(src, _ 
   New RectangleF(0, 0, 50, src.Height)), Bitmap).Clone

Either statement will clone the src image at (0,0,50, src.height) and return a bitmap object. I have simply then taken the bitmap object and cloned it into a picturebox so you can see the results.