|Title||Use DrawToBitmap to capture an image of a form in Visual Basic 2005|
|Description||This example shows how to use DrawToBitmap to capture an image of a form in Visual Basic 2005.|
|Keywords||DrawToBitmap, form image, capture form image, VB 2005, VB.NET|
|Categories||Graphics, VB.NET, Controls|
This method is a lot easier than older methods that require BitBlt and other unmanaged API function calls.
The GetFormImage function makes a Bitmap containing the form's image with or without borders. It starts by making a Bitmap big enough to hold the form's image with borders. It then uses the form's DrawToBitmap method to copy the form's image into the Bitmap. If include_borders is true, the function returns this Bitmap.
If include_borders is false, the program makes another smaller Bitmap to hold an image of the form's client area. It usdes PointToScreen to find the screen coordinates of the client area's upper left corner. It subtracts the form's upper left corner (including the borders) from that point to see how far the client area is offset in the form's image. It copies the client area's part of the image into the new Bitmap and returns it.
Private Function GetFormImage(ByVal include_borders As _
Boolean) As Bitmap
' Make the bitmap.
Dim wid As Integer = Me.Width
Dim hgt As Integer = Me.Height
Dim bm As New Bitmap(wid, hgt)
' Draw the form onto the bitmap.
Me.DrawToBitmap(bm, New Rectangle(0, 0, wid, hgt))
' If we want the borders, return the bitmap.
If include_borders Then Return bm
' Make a smaller bitmap without borders.
wid = Me.ClientSize.Width
hgt = Me.ClientSize.Height
Dim bm2 As New Bitmap(wid, hgt)
' Get the offset from the window's corner to its client
' area's corner.
Dim pt As New Point(0, 0)
pt = PointToScreen(pt)
Dim dx As Integer = pt.X - Me.Left
Dim dy As Integer = pt.Y - Me.Top
' Copy the part of the original bitmap that we want
' into the bitmap.
Dim gr As Graphics = Graphics.FromImage(bm2)
gr.DrawImage(bm, 0, 0, New Rectangle(dx, dy, wid, hgt), _