python - 使用win32api python捕获屏幕截图返回黑色图像
问题描述
我使用以下代码示例来捕获屏幕截图:
https://stackoverflow.com/a/3260811 https://stackoverflow.com/a/24352388/5858697
在截取 Firefox 或 chrome 的屏幕截图时,它们会返回一个空白的黑色图像。捕获记事本的屏幕截图效果很好。我对此进行了一些研究,我认为这是因为它们是 gpu 加速的。其他屏幕截图库可以工作,但我需要它,以便即使当前不可见,我也可以捕获应用程序的屏幕截图。
有没有人解决过类似的问题,或者有人能指出我正确的方向吗?谢谢你。
解决方案
根据@Barmak 之前的回答,我将 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 使用无窗口控件。
如果你想得到 Firefox 的句柄,你可能需要UI Automation。
详细解释请参考@IInspectable 的回答。
推荐阅读
- python - 使用 Python 理解二叉搜索树插入
- ios - 插入协议中的 viewDidLoad()
- java - 关闭/打开连接是否违反不变性?
- javascript - jQuery 使用 $(this) 并悬停在一起
- javascript - 将值从 node.js 传递给 javascript
- node.js - Kudu 控制台挂在 npm install 上
- ibm-mobilefirst - 如何将 IBM MobileFirst 安装为集群
- android - Android 强制压缩带有 jpg 扩展名的 sqlite
- android - 启动画面未按预期工作 - Xamarin
- php - 带有 IN 子句和 LIMIT 的 PHP PDO