Skip to content

Instantly share code, notes, and snippets.

@Crozzers
Created December 5, 2022 21:36
Show Gist options
  • Save Crozzers/e42237b4a87cca28411810cfc591ff9d to your computer and use it in GitHub Desktop.
Save Crozzers/e42237b4a87cca28411810cfc591ff9d to your computer and use it in GitHub Desktop.
# Sources:
# https://stackoverflow.com/questions/69712306/list-all-windows-with-win32gui
# http://timgolden.me.uk/pywin32-docs/win32gui__GetWindowRect_meth.html
# http://timgolden.me.uk/pywin32-docs/win32gui__MoveWindow_meth.html
# Todo:
# https://learn.microsoft.com/en-us/windows/win32/winmsg/wm-settingchange
# https://stackoverflow.com/questions/5981520/detect-external-display-being-connected-or-removed-under-windows-7
import win32gui
import time
def capture_snapshot():
def callback(hwnd, extra):
if win32gui.IsWindowVisible(hwnd):
title = win32gui.GetWindowText(hwnd)
rect = win32gui.GetWindowRect(hwnd)
if not title or rect == (0, 0, 0, 0):
return
snapshot[hwnd] = rect
snapshot = {}
win32gui.EnumWindows(callback, None)
return snapshot
def restore_snapshot(snap: dict):
def callback(hwnd, extra):
if hwnd not in snap:
return
title = win32gui.GetWindowText(hwnd)
rect = snap[hwnd]
if win32gui.GetWindowRect(hwnd) == rect:
return
win32gui.MoveWindow(hwnd, *rect[:2], rect[2] - rect[0], rect[3] - rect[1], 0)
win32gui.EnumWindows(callback, None)
snap = capture_snapshot()
print('Now move some stuff')
for i in range(5):
time.sleep(1)
print(5 - i)
print('Restore snapshot')
restore_snapshot(snap)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment