pyautogui 和 win32gui 屏幕截图背景窗口

时间:2021-06-13 07:39:08

标签: python pywin32 pyautogui

我正在尝试使用特定背景窗口的 pyautogui 进行屏幕截图,而不将其放在前台,我该怎么做? 这是我开始的项目,但我不知道下一步是什么

在这个例子中,chrome.exe 在后台运行,我试图在不将窗口置于前台的情况下进行屏幕截图

谢谢

#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 个答案:

答案 0 :(得分:0)

pyautogui 只能截屏。我们可以使用 win32ui.createBitmap() 截取背景窗口。复制 original answer 并进行一些修改以避免其评论中描述的黑色图像问题:

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')