|
|
Title | Grab the desktop image in VB .NET |
Description | This example shows how to grab the desktop image in VB .NET. |
Keywords | desktop image, background, VB.NET |
Categories | Graphics, 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)
MessageBox.Show("OK")
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, _
SRCCOPY)
' Release the bitmap's and desktop's DCs.
bm_gr.ReleaseHdc(bm_hdc)
ReleaseDC(desktop_win, desktop_dc)
' Return the result.
Return bm
End Function
|
|
|
|
|
|