What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleGrab the desktop image in VB .NET
DescriptionThis example shows how to grab the desktop image in VB .NET.
Keywordsdesktop image, background, VB.NET
CategoriesGraphics, Windows
The key to the program is the DesktopImage function, which returns a Bitmap holding the desktop's image. When the user clicks Go, the program simply calls the function to get the Bitmap and then uses the Bitmap's Save method to save it into a file.
' Save the desktop image.
Private Sub btnGo_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnGo.Click
    DesktopImage().Save(txtFile.Text, ImageFormat.Bmp)
End Sub
The DesktopImage function uses the GetDesktopWindow API function to get the hWnd of the desktop window. It uses GetDC to get a device context for that window. It uses Screen.GetBounds to see how big the desktop is.

Next the function makes a Bitmap big enough to hold the desktop's image, creates a Graphics object attached to it, and gets the Bitmap's device context.

The function then uses StretchBlt to copy the desktop window's image onto the Bitmap. It releases the Bitmap's and desktop's device context, and returns the Bitmap.

' Return an image of the desktop.
Private Function DesktopImage() As Bitmap
    ' Get the desktop size in pixels.
    Dim desktop_win As Int32 = GetDesktopWindow()
    Dim desktop_dc As Int32 = GetDC(desktop_win)
    Dim desktop_bounds As Rectangle = Screen.GetBounds(New _
        Point(1, 1))
    Dim desktop_wid As Int32 = desktop_bounds.Width
    Dim desktop_hgt As Int32 = desktop_bounds.Height

    ' Make a Bitmap to hold the image.
    Dim bm As New Bitmap(desktop_wid, desktop_hgt)
    Dim bm_gr As Graphics = Graphics.FromImage(bm)
    Dim bm_hdc As IntPtr = bm_gr.GetHdc

    ' Copy the desktop's image.
    StretchBlt( _
        bm_hdc, 0, 0, desktop_wid, desktop_hgt, _
        desktop_dc, 0, 0, desktop_wid, desktop_hgt, _

    ' Release the bitmap's  and desktop's DCs.
    ReleaseDC(desktop_win, desktop_dc)

    ' Return the result.
    Return bm
End Function
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.