Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
 
TitleSave a form's decorated image into a bitmap file in VB.NET
DescriptionThis example shows how to save a form's decorated image into a bitmap file in VB.NET. It makes a Bitmap, uses BitBlt to copy the form's image into it, and saves the result into a file.
Keywordsprint screen, screen capture, form image, save form image
CategoriesGraphics, VB.NET
 
Thanks to ViNEGAR for the hint about using GetWindowDC(Me.Handle).

When the user clicks the Save button, the program calls the GetDecoratedFormImage subroutine to make a Bitmap holding an image of the form's contents. It calls that object's Save method to save the image in a file.

Subroutine GetDecoratedFormImage gets a Graphics object for the form. It makes a Bitmap big enough to hold the image and gets a Graphics object for it. It then gets the device context handles (hDC) for the two Graphics objects and uses BitBlt to copy the form's image into the Bitmap.

 
Private 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 _
    System.Int32) As Boolean
Private Const SRCCOPY As Integer = &HCC0020

' Save the picture.
Private Sub btnSave_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnSave.Click
    Dim bm As Bitmap = GetDecoratedFormImage()
    bm.Save(txtFile.Text, ImageFormat.Bmp)
    Beep()
End Sub

' Get an image of the form plus its decoration
' (borders, title bar, etc).
Private Function GetDecoratedFormImage() As Bitmap
    ' Get this form's Graphics object.
    Dim me_gr As Graphics = Me.CreateGraphics

    ' Make a Bitmap to hold the image.
    Dim bm As New Bitmap(Me.Width, Me.Height, me_gr)
    Dim bm_gr As Graphics = me_gr.FromImage(bm)
    Dim bm_hdc As IntPtr = bm_gr.GetHdc

    ' Get the form's hDC. We must do this after 
    ' creating the new Bitmap, which uses me_gr.
    Dim me_hdc As IntPtr = GetWindowDC(Me.Handle)

    ' BitBlt the form's image onto the Bitmap.
    BitBlt(bm_hdc, 0, 0, Me.Width, Me.Height, _
        me_hdc, 0, 0, SRCCOPY)
    bm_gr.ReleaseHdc(bm_hdc)

    ' Return the result.
    Return bm
End Function
 
To copy only the form's client area without the decoration (borders, title bar, and so forth), see this example.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated