Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 26 additions & 16 deletions src/capture_windows.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from __future__ import annotations
from typing import Dict

from ctypes import windll
from ctypes.wintypes import LONG, RECT, HBITMAP
from packaging import version
from win32 import win32gui
import platform
import pywintypes
import numpy as np
import win32ui
import win32con
Expand Down Expand Up @@ -45,25 +47,33 @@ def capture_region(hwnd: int, rect: RECT):
def __get_image(hwnd: int, rect: RECT, print_window: bool = False):
width: LONG = rect.right - rect.left
height: LONG = rect.bottom - rect.top
windowDC: int = win32gui.GetWindowDC(hwnd)
dcObject = win32ui.CreateDCFromHandle(windowDC)

# Causes a 10-15x performance drop. But allows recording hardware accelerated windows
if (print_window):
windll.user32.PrintWindow(hwnd, dcObject.GetSafeHdc(), PW_RENDERFULLCONTENT)

compatibleDC = dcObject.CreateCompatibleDC()
bitmap: HBITMAP = win32ui.CreateBitmap()
bitmap.CreateCompatibleBitmap(dcObject, width, height)
compatibleDC.SelectObject(bitmap)
compatibleDC.BitBlt((0, 0), (width, height), dcObject, (rect.left, rect.top), win32con.SRCCOPY)
# If the window closes while it's being manipulated, it could cause a crash
try:
windowDC: int = win32gui.GetWindowDC(hwnd)
dcObject = win32ui.CreateDCFromHandle(windowDC)

# Causes a 10-15x performance drop. But allows recording hardware accelerated windows
if (print_window):
windll.user32.PrintWindow(hwnd, dcObject.GetSafeHdc(), PW_RENDERFULLCONTENT)

compatibleDC = dcObject.CreateCompatibleDC()
bitmap: HBITMAP = win32ui.CreateBitmap()
bitmap.CreateCompatibleBitmap(dcObject, width, height)
compatibleDC.SelectObject(bitmap)
compatibleDC.BitBlt((0, 0), (width, height), dcObject, (rect.left, rect.top), win32con.SRCCOPY)
except (win32ui.error, pywintypes.error):
errorImage = np.array([0, 0, 0, 1], dtype="uint8")
return errorImage

image: np._BufferType = np.frombuffer(bitmap.GetBitmapBits(True), dtype='uint8')
image.shape = (height, width, 4)

dcObject.DeleteDC()
compatibleDC.DeleteDC()
win32gui.ReleaseDC(hwnd, windowDC)
win32gui.DeleteObject(bitmap.GetHandle())
try:
dcObject.DeleteDC()
compatibleDC.DeleteDC()
win32gui.ReleaseDC(hwnd, windowDC)
win32gui.DeleteObject(bitmap.GetHandle())
except win32ui.error:
pass

return image