PyWin32无法捕获某些窗口,导致黑屏(Python,Windows)

感谢Github上的@wchill找到了这个解决方案(链接)!适用于Windows,适用于硬件加速和被其他窗口遮挡的窗口。

import cv2
import numpy as np
from ctypes import windll
import win32gui
import win32ui


def capture_win_alt(hwnd=None, bmpFileName='hwnd.bmp', jpgFileName='hwnd.png', delete=False,
                    program_windowTitle='微信', program_className='WeChatMainWndForPC'):
    # Adapted from https://stackoverflow.com/questions/19695214/screenshot-of-inactive-window-printwindow-win32gui
    windll.user32.SetProcessDPIAware()
    if not hwnd:
        hwnd = win32gui.FindWindow(None, program_windowTitle)
        # hwnd = win32gui.FindWindowEx(0, 0, program_className, program_windowTitle)
    logger.info(f'hwnd: {hwnd}')
    if not hwnd:
        return None
    left, top, right, bottom = win32gui.GetClientRect(hwnd)
    w = right - left
    h = bottom - top
    hwnd_dc = win32gui.GetWindowDC(hwnd)
    mfc_dc = win32ui.CreateDCFromHandle(hwnd_dc)
    save_dc = mfc_dc.CreateCompatibleDC()
    bitmap = win32ui.CreateBitmap()
    bitmap.CreateCompatibleBitmap(mfc_dc, w, h)
    save_dc.SelectObject(bitmap)
    # If Special K is running, this number is 3. If not, 1
    result = windll.user32.PrintWindow(hwnd, save_dc.GetSafeHdc(), 3)
    bmpinfo = bitmap.GetInfo()
    bmpstr = bitmap.GetBitmapBits(True)
    img = np.frombuffer(bmpstr, dtype=np.uint8).reshape((bmpinfo["bmHeight"], bmpinfo["bmWidth"], 4))
    img = np.ascontiguousarray(img)[..., :-1]  # make image C_CONTIGUOUS and drop alpha channel
    if not result:  # result should be 1
        win32gui.DeleteObject(bitmap.GetHandle())
        save_dc.DeleteDC()
        mfc_dc.DeleteDC()
        win32gui.ReleaseDC(hwnd, hwnd_dc)
        raise RuntimeError(f"Unable to acquire screenshot! Result: {result}")
    cv2.imwrite(jpgFileName, img)
    return img


def main():
    WINDOW_NAME = "Swapface"
    while cv2.waitKey(1) != ord('q'):
        screenshot = capture_win_alt(program_windowTitle=WINDOW_NAME)
        if screenshot is not None:
            print(screenshot.shape)


if __name__ == '__main__':
    main()

  • 2
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值