0

im trying to take screenshoot with pyautogui of specific background window without put it in foreground, how can i make that ? this is my started project but i dont know what is the next step

in this example, chrome.exe run in background and i m trying to take screenshoot without put the window in forground

thanks

#pip install pywin32

import pyautogui
import win32gui, win32api, win32con
import time

def takescreen():
    myScreenshot = pyautogui.screenshot()
    myScreenshot.save(r'screenshoot.png')

hwnd = win32gui.FindWindow(None, 'Chrome')
hwndChild = win32gui.GetWindow(hwnd, win32con.GW_CHILD)
hwndChild2 = win32gui.GetWindow(hwndChild, win32con.GW_CHILD)


##NEXT STEP


1 Answers1

0

pyautogui can only capture the screen. We can screenshot background windows using win32ui.createBitmap(). Replicating the original answer with some modifications to avoid the black image issue describe in its comments:

def takescreen(hwnd,width,height,filename):
    #hwnd is window handle
    #width, height are in pixels
    #filename is name of screenshot file
    
    hwndDC = win32gui.GetWindowDC(hwnd)
    mfcDC  = win32ui.CreateDCFromHandle(hwndDC)
    saveDC = mfcDC.CreateCompatibleDC()
   
    saveBitMap = win32ui.CreateBitmap()
    saveBitMap.CreateCompatibleBitmap(mfcDC, width, height)    
    saveDC.SelectObject(saveBitMap)    
    result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 2)
    bmpinfo = saveBitMap.GetInfo()
    bmpstr = saveBitMap.GetBitmapBits(True)
    im = Image.frombuffer(
        'RGB',
        (bmpinfo['bmWidth'], bmpinfo['bmHeight']),
        bmpstr, 'raw', 'BGRX', 0, 1)
    
    win32gui.DeleteObject(saveBitMap.GetHandle())
    saveDC.DeleteDC()
    mfcDC.DeleteDC()
    win32gui.ReleaseDC(hwnd, hwndDC)

    if result == 1:
        #PrintWindow Succeeded
        im.save(filename)

#sample usage
hwnd = win32gui.FindWindow(None, 'Chrome')
takescreen(hwnd,1024,768,'screenshot.png')    
PG11
  • 133
  • 4