【发布时间】:2018-11-30 05:22:05
【问题描述】:
我正在尝试使用 Python 3.6 为 PIL/Numpy(每个屏幕截图约 0.01 秒)处理准备好快速屏幕截图。理想情况下,窗口不需要在前台,即即使另一个窗口覆盖它,屏幕截图仍然成功。
到目前为止,我已经从这个问题修改了 python 3 的代码:Python Screenshot of inactive window PrintWindow + win32gui
但是,它得到的只是黑色图像。
import win32gui
import win32ui
from ctypes import windll
from PIL import Image
hwnd = win32gui.FindWindow(None, 'Calculator')
# Get window bounds
left, top, right, bot = win32gui.GetWindowRect(hwnd)
w = right - left
h = bot - top
hwndDC = win32gui.GetWindowDC(hwnd)
mfcDC = win32ui.CreateDCFromHandle(hwndDC)
saveDC = mfcDC.CreateCompatibleDC()
saveBitMap = win32ui.CreateBitmap()
saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
saveDC.SelectObject(saveBitMap)
result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 1)
print(result)
bmp_info = saveBitMap.GetInfo()
bmp_str = saveBitMap.GetBitmapBits(True)
print(bmp_str)
im = Image.frombuffer(
'RGB',
(bmp_info['bmWidth'], bmp_info['bmHeight']),
bmp_str, 'raw', 'BGRX', 0, 1)
win32gui.DeleteObject(saveBitMap.GetHandle())
saveDC.DeleteDC()
mfcDC.DeleteDC()
win32gui.ReleaseDC(hwnd, hwndDC)
if result == 1:
im.save("screenshot.png")
【问题讨论】:
-
在 Windows 10 中,计算器是商店应用程序,而不是本机 Win32 应用程序,因此此方法不起作用。您必须确保目标应用程序处于前台 (
SetForegroundWindow),然后在计算器应用程序的特定坐标处截取整个窗口的屏幕截图。 -
我得到了任何窗口的黑色屏幕截图,而不仅仅是计算器,这个想法是捕获不在前台的窗口的内容。
标签: python