30 lines
1.1 KiB
Python
30 lines
1.1 KiB
Python
"""Capture a window via PrintWindow (works without screen access)."""
|
|
import sys, ctypes
|
|
from ctypes import wintypes
|
|
import win32gui, win32ui, win32con
|
|
from PIL import Image
|
|
|
|
def capture(hwnd, out):
|
|
left, top, right, bottom = win32gui.GetWindowRect(hwnd)
|
|
w, h = right - left, bottom - top
|
|
hwnd_dc = win32gui.GetWindowDC(hwnd)
|
|
mfc_dc = win32ui.CreateDCFromHandle(hwnd_dc)
|
|
save_dc = mfc_dc.CreateCompatibleDC()
|
|
bmp = win32ui.CreateBitmap()
|
|
bmp.CreateCompatibleBitmap(mfc_dc, w, h)
|
|
save_dc.SelectObject(bmp)
|
|
# PW_RENDERFULLCONTENT = 2
|
|
ok = ctypes.windll.user32.PrintWindow(hwnd, save_dc.GetSafeHdc(), 2)
|
|
info = bmp.GetInfo()
|
|
bits = bmp.GetBitmapBits(True)
|
|
img = Image.frombuffer('RGB', (info['bmWidth'], info['bmHeight']), bits, 'raw', 'BGRX', 0, 1)
|
|
img.save(out)
|
|
win32gui.DeleteObject(bmp.GetHandle())
|
|
save_dc.DeleteDC()
|
|
mfc_dc.DeleteDC()
|
|
win32gui.ReleaseDC(hwnd, hwnd_dc)
|
|
print('PrintWindow ok=', ok, 'size=', img.size, '->', out)
|
|
|
|
if __name__ == '__main__':
|
|
capture(int(sys.argv[1]), sys.argv[2])
|