Skip to content

Instantly share code, notes, and snippets.

@qqwqqw689
Last active September 7, 2024 06:26
Show Gist options
  • Save qqwqqw689/88afc86588b0689ad0f263f81c755423 to your computer and use it in GitHub Desktop.
Save qqwqqw689/88afc86588b0689ad0f263f81c755423 to your computer and use it in GitHub Desktop.
Window Screen Capture Using Pywin32.
import win32gui, win32ui, win32con

def test_get_screenshot():
    # define your monitor width and height
    w, h = 1920, 1080

    # for now we will set hwnd to None to capture the primary monitor
    #hwnd = win32gui.FindWindow(None, window_name)
    hwnd = None

    # get the window image data
    wDC = win32gui.GetWindowDC(hwnd)
    dcObj = win32ui.CreateDCFromHandle(wDC)
    cDC = dcObj.CreateCompatibleDC()
    dataBitMap = win32ui.CreateBitmap()
    dataBitMap.CreateCompatibleBitmap(dcObj, w, h)
    cDC.SelectObject(dataBitMap)
    cDC.BitBlt((0, 0), (w, h), dcObj, (0, 0), win32con.SRCCOPY)
    # use numpy
    # result = numpy.frombuffer(dataBitMap.GetBitmapBits(True), dtype=numpy.uint8).reshape(1080,1920,4)
    # save the image as a bitmap file
    dataBitMap.SaveBitmapFile(cDC, 'debug.bmp')

    # free resources
    dcObj.DeleteDC()
    cDC.DeleteDC()
    win32gui.ReleaseDC(hwnd, wDC)
    win32gui.DeleteObject(dataBitMap.GetHandle())
    
def get_screenshot():
   # define your monitor width and height
   w, h = 1920, 1080

   # for now we will set hwnd to None to capture the primary monitor
   #hwnd = win32gui.FindWindow(None, window_name)
   hwnd = None

   # get the window image data
   wDC = win32gui.GetWindowDC(hwnd)
   dcObj = win32ui.CreateDCFromHandle(wDC)
   cDC = dcObj.CreateCompatibleDC()
   dataBitMap = win32ui.CreateBitmap()
   dataBitMap.CreateCompatibleBitmap(dcObj, w, h)
   cDC.SelectObject(dataBitMap)
   cDC.BitBlt((0, 0), (w, h), dcObj, (0, 0), win32con.SRCCOPY)

   # convert the raw data into a format opencv can read
   signedIntsArray = dataBitMap.GetBitmapBits(True)
   img = np.fromstring(signedIntsArray, dtype='uint8')
   img.shape = (h, w, 4)

   # free resources
   dcObj.DeleteDC()
   cDC.DeleteDC()
   win32gui.ReleaseDC(hwnd, wDC)
   win32gui.DeleteObject(dataBitMap.GetHandle())

   # drop the alpha channel to work with cv.matchTemplate()
   img = img[...,:3]

   # make image C_CONTIGUOUS to avoid errors with cv.rectangle()
   img = np.ascontiguousarray(img)

   return img
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment