-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcapture.py
More file actions
47 lines (37 loc) · 1.49 KB
/
Copy pathcapture.py
File metadata and controls
47 lines (37 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"""Windows API 窗口截图"""
import ctypes
import cv2
import numpy as np
import win32con
import win32gui
import win32ui
def capture_window_bgr(hwnd: int) -> np.ndarray:
"""通过 PrintWindow API 抓取窗口内容,即使被遮挡也能截取。"""
client_rect = win32gui.GetClientRect(hwnd)
client_w = client_rect[2] - client_rect[0]
client_h = client_rect[3] - client_rect[1]
if client_w <= 0 or client_h <= 0:
return np.zeros((1, 1, 3), dtype=np.uint8)
hwndDC = win32gui.GetDC(hwnd)
mfcDC = win32ui.CreateDCFromHandle(hwndDC)
saveDC = mfcDC.CreateCompatibleDC()
saveBitMap = win32ui.CreateBitmap()
saveBitMap.CreateCompatibleBitmap(mfcDC, client_w, client_h)
old_bitmap = saveDC.SelectObject(saveBitMap)
try:
result = ctypes.windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 3)
if result != 1:
saveDC.BitBlt((0, 0), (client_w, client_h), mfcDC, (0, 0), win32con.SRCCOPY)
signedIntsArray = saveBitMap.GetBitmapBits(True)
img = np.frombuffer(signedIntsArray, dtype="uint8")
expected_size = client_h * client_w * 4
if len(img) != expected_size:
img = np.zeros(expected_size, dtype="uint8")
img.shape = (client_h, client_w, 4)
finally:
saveDC.SelectObject(old_bitmap)
win32gui.DeleteObject(saveBitMap.GetHandle())
saveDC.DeleteDC()
mfcDC.DeleteDC()
win32gui.ReleaseDC(hwnd, hwndDC)
return cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)