The standard way to copy the contents of the screen or a window to a picture box requires you to use a lot of API functions, such as BitBlt. A simpler approach is possible, though: you just have to simulate the typing of the Print Screen key (or Alt+Print Screen if you want to copy the contents of the active window) and then retrieve the contents of the Clipboard.
Unfortunately, you can’t use SendKeys to press those keys, and you’ve to resort to the keybd_event API function. Here is a function that encapsulates all the low level details and also correctly restore the original contents of the Clipboard.
Private Declare Sub keybd_event Lib "user32" (ByVal bVk As Byte, _ ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)Private Const KEYEVENTF_KEYUP = &H2' Return the current contents of the screen or the active window'' It works by simulating the typing of the Print-Screen key' (and Alt key if ActiveWindow is True), which dumps the screen' to the clipboard. The original contents of the clipboard is then' restored, but this action might affect the behavior of other' applications that are monitoring the clipboard.Function GetScreenBitmap(Optional ActiveWindow As Boolean) As Picture ' save the current picture in the clipboard, if any Dim pic As StdPicture Set pic = Clipboard.GetData(vbCFBitmap) ' Alt-Print Screen captures the active window only If ActiveWindow Then ' Press the Alt key keybd_event vbKeyMenu, 0, 0, 0 End If ' Press the Print Screen key keybd_event vbKeySnapshot, 0, 0, 0 DoEvents ' Release the Print Screen key keybd_event vbKeySnapshot, 0, KEYEVENTF_KEYUP, 0 If ActiveWindow Then ' Release the Alt key keybd_event vbKeyMenu, 0, KEYEVENTF_KEYUP, 0 End If DoEvents ' return the bitmap now in the clipboard Set GetScreenBitmap = Clipboard.GetData(vbCFBitmap) ' restore the original contents of the clipboard Clipboard.SetData pic, vbCFBitmap End Function
Using the GenScreenBitmap is really straightforward:
' capture the contents of the screen to a picture boxSet Picture1.Picture = GenScreenBitmap()' capture the contents of the active window to a picture boxSet Picture2.Picture = GenScreenBitmap(True)