How to capture specific area of inactive window in python?
- it cannot bring window foreground it has to stay in the background
- it cannot use screenshot method because other windows may get in the way
- it has to be specific area with defined from top, left position to bottom,
right position not the whole screen
I’ve managed to fulfill two first conditions however I struggle with last one, here is my code
import win32gui, win32ui
from ctypes import windll
from PIL import Image
def capture_screen():
hwndDC = win32gui.GetWindowDC(hwnd)
mfcDC = win32ui.CreateDCFromHandle(hwndDC)
saveDC = mfcDC.CreateCompatibleDC()
rect = win32gui.GetWindowRect(hwnd)
saveBitMap = win32ui.CreateBitmap()
saveBitMap.CreateCompatibleBitmap(mfcDC, rect[2], rect[3]) # figure a way to capture only a part of the screen instead
saveDC.SelectObject(saveBitMap)
result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 2)
bmpinfo = saveBitMap.GetInfo()
bmpstr = saveBitMap.GetBitmapBits(True)
image = Image.frombuffer('RGB', (bmpinfo['bmWidth'], bmpinfo['bmHeight']), bmpstr, 'raw', 'BGRX', 0, 1)
win32gui.DeleteObject(saveBitMap.GetHandle())
saveDC.DeleteDC()
mfcDC.DeleteDC()
win32gui.ReleaseDC(hwnd, hwndDC)
return image
WINDOW_NAME = 'Play Chrome Dinosaur Game Online - elgooG - Google Chrome'
hwnd = win32gui.FindWindow(None, WINDOW_NAME)
screen_capture = capture_screen()
screen_capture.save('window_capture.png')
Here is the picture being saved:
Full screen dino
Here is my goal:
Desired output