用win32api截屏pythonreturns黑图

Capturing screenshots with win32api python returns black image

我使用了以下代码示例来捕获屏幕截图:

在截取 Firefox 或 chrome 的屏幕截图时,他们 return 一张空白的黑色图像。捕获记事本的屏幕截图工作正常。我对此做了一些研究,我认为这是因为它们是 gpu 加速的。其他屏幕截图库可以使用,但我需要它,这样我就可以捕获应用程序的屏幕截图,即使它当前不可见。

有没有人解决过类似的问题或者有人可以指出正确的方向吗?谢谢。

的基础上,我将C++代码转为python,现在可以了。

import win32gui
import win32ui
import win32con
from ctypes import windll
from PIL import Image
import time
import ctypes

hwnd_target = 0x00480362 #Chrome handle be used for test 

left, top, right, bot = win32gui.GetWindowRect(hwnd_target)
w = right - left
h = bot - top

win32gui.SetForegroundWindow(hwnd_target)
time.sleep(1.0)

hdesktop = win32gui.GetDesktopWindow()
hwndDC = win32gui.GetWindowDC(hdesktop)
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', 0, 1)

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

if result == None:
    #PrintWindow Succeeded
    im.save("test.png")

请注意:Firefox 使用 Windowless Controls

如果想获取Firefox的句柄,可能需要UI Automation.

详细解释请参考.