如何使用python拍摄重叠活动窗口的快照?

问题描述

我尝试在Windows vm中执行以下代码,并且工作正常。但是,当涉及本机Windows OS时,这将输出显示为黑色屏幕截图。我试图捕获一个后台运行的chrome窗口,并与某些应用程序的另一个窗口X重叠。我无法真正弄清楚为什么它在Windows vm中而不是在本机Windows os中工作。我无法弄清楚是什么阻止了本机Windows OS执行类似的代码并提供与Windows vm相同的输出。 仅当chrome窗口设置为前台并且没有任何其他窗口重叠时,该代码才能在本机窗口os中起作用并提供屏幕截图。

import time 
import win32gui
import os
import win32con
import win32ui
from ctypes import windll
from datetime import datetime
from os.path import join 
from PIL import Image


def ss_windows(t,t_x,win_name):
    """
        This function will screenshot the `win_name` window every `t` seconds,until we interrupt the script manually or `t_x` seconds have elapsed 
        since we started the script.
    """
    while True:
        start = time.time()
        while time.time() - start < t_x:
            toplist,winlist = [],[]
            def enum_cb(hwnd,results):
                winlist.append((hwnd,win32gui.GetwindowText(hwnd)))
            win32gui.EnumWindows(enum_cb,toplist)
            # Now look for the window
            wins = [(hwnd,title) for hwnd,title in winlist if win_name in title.lower()]
            # check if window is open or not
            if len(wins) == 0:
                print(f"It seems like {win_name} is not open in the background. Please open it and try again.")
                time.sleep(3)
                continue
            # Now get window handle of the window
            wins = wins[0] # get the first window from list
            hwnd = wins[0] 
            
            left,top,right,bot = win32gui.GetwindowRect(hwnd)# get the bBox
            w = right - left
            h = bot - top

            #Uncomment the below 3 lines for setting the window to foreground

            # win32gui.SetForegroundWindow(hwnd)
            # hdesktop = win32gui.GetDesktopWindow()
            # hwndDC = win32gui.GetwindowDC(hdesktop)
            

            #comment the following line when window is set to foreground
            hwndDC = win32gui.GetwindowDC(hwnd)


            mfcDC  = win32ui.CreateDCFromHandle(hwndDC)
            saveDC = mfcDC.CreateCompatibleDC()
            saveBitMap = win32ui.CreateBitmap()
            saveBitMap.CreateCompatibleBitmap(mfcDC,w,h)
            saveDC.SelectObject(saveBitMap)

            result = saveDC.BitBlt((0,0),(w,h),mfcDC,(left,top),win32con.SRCcopY)
            
            bmpinfo = saveBitMap.GetInfo()
            bmpstr = saveBitMap.GetBitmapBits(True)

            im = Image.frombuffer('RGB',(bmpinfo['bmWidth'],bmpinfo['bmHeight']),bmpstr,'raw','BGRX',1)
            
            fname = datetime.Now().strftime("%H_%M_%s") + ".jpg"
            fpath = os.path.join('screenshots',fname)
            
            print(f"New screenshot saved at  {fpath}")
            

            win32gui.DeleteObject(saveBitMap.GetHandle())
            saveDC.DeleteDC()
            mfcDC.DeleteDC()
            win32gui.ReleaseDC(hwnd,hwndDC)

            if result == None:
                #Printwindow Succeeded
                im.save(fpath)

            time.sleep(t)


        break


if __name__ == '__main__':
    ss_windows(1,10,"chrome")

规格: Windows 10专业版, Python 3.8.5, Pywin32版本228

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)