-
-
Save spyoungtech/ca182fa433a7a792d3ef8b5740fdf00f to your computer and use it in GitHub Desktop.
ahk python active monitor script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import wmutil | |
from ahk import AHK, Window | |
import threading | |
import time | |
ahk = AHK() | |
registered_displays: set[wmutil.Monitor] = set() | |
def initialize(): | |
registered_displays.clear() | |
ahk.clear_hotkeys() | |
ahk.add_hotkey('#`', initialize) | |
ahk.add_hotkey('#Home', move_active_window_to_primary_monitor) | |
ahk.add_hotkey('#F1', identify) | |
for monitor in wmutil.enumerate_monitors(): | |
display_num = monitor.name[-1] | |
assert display_num.isdigit() | |
registered_displays.add(monitor) | |
ahk.add_hotkey(f'#{display_num}', monitor.set_primary) | |
def check_monitor_changes(): | |
while True: | |
time.sleep(5) | |
monitors = wmutil.enumerate_monitors() | |
if len(monitors) != len(registered_displays): | |
initialize() | |
continue | |
for monitor in monitors: | |
display_num = monitor.name[-1] | |
assert display_num.isdigit() | |
if display_num not in registered_displays: | |
initialize() | |
def move_active_window_to_primary_monitor(): | |
win = ahk.get_active_window() | |
mon = wmutil.get_primary_monitor() | |
x, y = mon.position | |
win.move(x, y) | |
winpos = win.get_position() | |
w, h = mon.size | |
if winpos.height > h or winpos.width > w: | |
win.move(x, y, width=w, height=h) | |
def move_window_to_monitor_center(win: Window, mon: wmutil.Monitor) -> None: | |
winpos = win.get_position() | |
x, y = mon.position | |
w, h = mon.size | |
x += (w / 2) - winpos.width / 2 | |
y += (h / 2) - winpos.height / 2 | |
win.move(x, y) | |
def identify(): | |
windows = [] | |
for monitor in registered_displays: | |
title = f'monitor {monitor.name[-1]}' | |
ahk.msg_box(text=title, title=title, blocking=False) | |
win = ahk.win_wait(title=title) | |
win.always_on_top = True | |
windows.append(win) | |
move_window_to_monitor_center(win, monitor) | |
time.sleep(3) | |
for win in windows: | |
win.close() | |
if __name__ == '__main__': | |
initialize() | |
t = threading.Thread(target=check_monitor_changes, daemon=True) | |
t.start() | |
ahk.start_hotkeys() | |
ahk.block_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment