import ctypes, os, time
from ctypes import wintypes
import win32gui, win32ui
from PIL import Image

user32 = ctypes.windll.user32
hdesk = user32.OpenInputDesktop(0, False, 0x01FF)
if hdesk:
    user32.SetThreadDesktop(hdesk)

hwnds = [0xd0cec, 0xe207f6, 0x2f0bf4, 0x60b66]

def capture_win(h, name):
    rect = win32gui.GetClientRect(h)
    w = rect[2] - rect[0]
    h_h = rect[3] - rect[1]
    if w <= 0 or h_h <= 0: return
    hwndDC = win32gui.GetWindowDC(h)
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)
    saveDC = mfcDC.CreateCompatibleDC()
    saveBitMap = win32ui.CreateBitmap()
    saveBitMap.CreateCompatibleBitmap(mfcDC, w, h_h)
    saveDC.SelectObject(saveBitMap)
    user32.PrintWindow(h, saveDC.GetSafeHdc(), 0)
    bmpinfo = saveBitMap.GetInfo()
    bmpstr = saveBitMap.GetBitmapBits(True)
    img = Image.frombuffer('RGB', (bmpinfo['bmWidth'], bmpinfo['bmHeight']), bmpstr, 'raw', 'BGRX', 0, 1)
    img.save(f'c:/Projects/JX/logs/{name}.png')
    win32gui.DeleteObject(saveBitMap.GetHandle())
    saveDC.DeleteDC()
    mfcDC.DeleteDC()
    win32gui.ReleaseDC(h, hwndDC)
    print(f"Captured {hex(h)} -> c:/Projects/JX/logs/{name}.png")

for h in hwnds:
    if win32gui.IsWindow(h):
        capture_win(h, f'current_game_{h:x}')
