【问题标题】:Python - Screenshot of background/inactive windowPython - 背景/非活动窗口的屏幕截图
【发布时间】: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


【解决方案1】:

此代码适用于后台应用程序,而不是最小化。

import win32gui
import win32ui

def background_screenshot(hwnd, width, height):
    wDC = win32gui.GetWindowDC(hwnd)
    dcObj=win32ui.CreateDCFromHandle(wDC)
    cDC=dcObj.CreateCompatibleDC()
    dataBitMap = win32ui.CreateBitmap()
    dataBitMap.CreateCompatibleBitmap(dcObj, width, height)
    cDC.SelectObject(dataBitMap)
    cDC.BitBlt((0,0),(width, height) , dcObj, (0,0), win32con.SRCCOPY)
    dataBitMap.SaveBitmapFile(cDC, 'screenshot.bmp')
    dcObj.DeleteDC()
    cDC.DeleteDC()
    win32gui.ReleaseDC(hwnd, wDC)
    win32gui.DeleteObject(dataBitMap.GetHandle())

hwnd = win32gui.FindWindow(None, windowname)
background_screenshot(hwnd, 1280, 780)

【讨论】:

  • 使用 python 3.8 在 Windows 10 上导致黑屏
猜你喜欢
  • 1970-01-01
  • 2022-01-22
  • 2013-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多