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


2 Answers2

1

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
  • 155
  • 5
0

The original answer imports Image via import Image. If this is causing a problem for anyone, use from PIL import Image.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 04 '23 at 18:16
  • 2
    If you have a new question, please ask it by clicking the [Ask Question](https://stackoverflow.com/questions/ask) button. Include a link to this question if it helps provide context. - [From Review](/review/late-answers/34496812) – dpapadopoulos Jun 07 '23 at 15:15