What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleGrab the desktop image after a delay in VB .NET
DescriptionThis example shows how to grab the desktop image after a delay in VB .NET.
Keywordsdesktop image, background, VB.NET
CategoriesGraphics, Windows
I needed this feature to capture an image of the Task Manager.

When the user clicks the Go button, the program sets the tmrGrabDesktop Timer's Interval property to the number of seconds indicated and enables the Timer.

When the Timer fires, it disables itself and uses function DesktopImage to get a Bitmap holding the desktop's image and calls the Bitmap's Save method.

' Save the desktop image.
Private Sub btnGo_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnGo.Click
    btnGo.Enabled = False
    Me.Cursor = Cursors.WaitCursor
    tmrGrabDesktop.Interval = _
        CInt(Single.Parse(txtDelay.Text) * 1000)
    tmrGrabDesktop.Enabled = True
End Sub

' Save the desktop image.
Private Sub tmrGrabDesktop_Tick(ByVal sender As _
    System.Object, ByVal e As System.EventArgs) Handles _
    tmrGrabDesktop.Enabled = False
    DesktopImage().Save(txtFile.Text, ImageFormat.Bmp)
    Me.Cursor = Cursors.Default
    btnGo.Enabled = True
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.