Get a Picture of the Desktop's Contents
This tip shows how to get a picture of the entire desktop. You can use the picture that you get to draw onto (perhaps as the basis for a screen saver), or as a basis for capturing areas of the desktop.
Start a new project in VB. Add a new module, and add the following code:
Private Type RECT Left As Long Top As Long Right As Long Bottom As Long End Type Private Declare Function GetWindowRect Lib "user32" ( _ ByVal hWnd As Long, lpRect As RECT) As Long Private Declare Function DeleteDC Lib "gdi32" ( _ ByVal hDC As Long) As Long Private Declare Function CreateDCAsNull Lib "gdi32" Alias "CreateDCA" ( _ ByVal lpDriverName As String, lpDeviceName As Any, _ lpOutput As Any, lpInitData As Any) As Long Private Declare Function BitBlt Lib "gdi32" ( _ ByVal hDestDC As Long, ByVal x As Long, ByVal y As Long, ByVal nWidth As Long, ByVal nHeight As Long, ByVal hSrcDC As Long, ByVal xSrc As Long, ByVal ySrc As Long, ByVal dwRop As Long) As Long Private Const SRCCOPY = &HCC0020 ' (DWORD) dest = source Private Declare Function GetDesktopWindow Lib "user32" () As Long Public Sub CopyDesktop( _ ByRef objTo As Object _ ) Dim hWnd As Long Dim tR As RECT Dim hDC As Long ' Note: objTo must have hDC,Picture,Width and Height ' properties and should have AutoRedraw = True ' Get the size of the desktop window: hWnd = GetDesktopWindow() GetWindowRect hWnd, tR ' Set the object to the relevant size: objTo.Width = (tR.Right - tR.Left) * Screen.TwipsPerPixelX objTo.Height = (tR.Bottom - tR.Top) * Screen.TwipsPerPixelY ' Now get the desktop DC: hDC = CreateDCAsNull("DISPLAY", ByVal 0&, ByVal 0&, ByVal 0&) ' Copy the contents of the desktop to the object: BitBlt objTo.hDC, 0, 0, _ (tR.Right - tR.Left), (tR.Bottom - tR.Top), hDC, 0, 0, SRCCOPY ' Ensure we clear up DC GDI has given us: DeleteDC hDC End Sub
To try out the desktop capture, add a Picture Box to the project's form. Set the AutoRedraw property of the Picture Box to True. Then add a Command button. Make sure that the Command button is above the Picture Box in the form, otherwise when you capture the desktop and get an Image of your form, it can get a little confusing working out which is the real button to click on! Add the following code to the Command button's click event:
Private Sub Command1_Click() Picture1.Cls CopyDesktop Picture1 Picture1.Refresh End Sub
When you click on the button, the Picture will get a complete image of the desktop. It will also be resized to the size of the desktop.