Skip to content

Instantly share code, notes, and snippets.

@rebane2001
Created May 11, 2024 09:29
Show Gist options
  • Save rebane2001/9df65c7367a1bf0db773b6032ba0d7a0 to your computer and use it in GitHub Desktop.
Save rebane2001/9df65c7367a1bf0db773b6032ba0d7a0 to your computer and use it in GitHub Desktop.
Example of using some basic winuser.h calls to get info and resize a window in Python using ctypes
import os
import time
import ctypes
from ctypes import wintypes
def get_window_title(h_wnd):
max_length = 255
title = ctypes.create_unicode_buffer(max_length)
ctypes.windll.user32.GetWindowTextW(h_wnd, title, max_length)
return title.value
def get_window_pid(h_wnd):
pid = wintypes.DWORD()
ctypes.windll.user32.GetWindowThreadProcessId(h_wnd, ctypes.byref(pid))
return pid.value
def get_foreground_window():
return ctypes.windll.user32.GetForegroundWindow()
def get_window_pos(h_wnd):
lp_rect = wintypes.RECT()
ctypes.windll.user32.GetWindowRect(h_wnd, ctypes.byref(lp_rect))
return lp_rect.left, lp_rect.top, lp_rect.right - lp_rect.left, lp_rect.bottom - lp_rect.top
def set_window_pos(h_wnd, x, y, w, h):
SWP_NOZORDER = 0x0004
ctypes.windll.user32.SetWindowPos(h_wnd, 0, x, y, w, h, SWP_NOZORDER)
last_output_len = 0
while True:
h_wnd = get_foreground_window()
title = get_window_title(h_wnd)
pid = get_window_pid(h_wnd)
itself = pid == os.getpid() or pid == os.getppid()
output = f"{h_wnd = }, {pid = }, {title = }{' (itself)' if itself else ''}"
print(output + " "*(last_output_len - len(output)) if len(output) < last_output_len else output, end='\r', flush=True)
last_output_len = len(output)
x, y, w, h = get_window_pos(h_wnd)
set_window_pos(h_wnd, x, y, w, h)
time.sleep(0.1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment