Skip to content

Instantly share code, notes, and snippets.

@Lxtharia
Created September 26, 2024 10:16
Show Gist options
  • Save Lxtharia/7790d7727c096cd981dcb98c9424e4f2 to your computer and use it in GitHub Desktop.
Save Lxtharia/7790d7727c096cd981dcb98c9424e4f2 to your computer and use it in GitHub Desktop.
Autohotkey script to move around (focus) visible windows on Windows using Win+hjkl
#Requires AutoHotkey v2.0
; Window styles for easier filtering of valid windows
styles := Map(
"WS_BORDER", 0x800000, "WS_POPUP", 0x80000000,
"WS_CAPTION", 0xC00000, "WS_CLIPSIBLINGS", 0x4000000,
"WS_DISABLED", 0x8000000, "WS_DLGFRAME", 0x400000,
"WS_GROUP", 0x20000, "WS_HSCROLL", 0x100000,
"WS_MAXIMIZE", 0x1000000, "WS_MAXIMIZEBOX", 0x10000,
"WS_MINIMIZE", 0x20000000, "WS_MINIMIZEBOX", 0x20000,
"WS_OVERLAPPED", 0x0, "WS_OVERLAPPEDWINDOW", 0xCF0000,
"WS_POPUPWINDOW", 0x80880000, "WS_SIZEBOX", 0x40000,
"WS_SYSMENU", 0x80000, "WS_TABSTOP", 0x10000,
"WS_THICKFRAME", 0x40000, "WS_VSCROLL", 0x200000,
"WS_VISIBLE", 0x10000000, "WS_CHILD", 0x40000000
)
#h::SelectWindow("left")
#j::SelectWindow("right")
#k::SelectWindow("up")
#l::SelectWindow("down")
; Disabling Win+L required setting registry key: https://www.autohotkey.com/board/topic/95733-wanna-override-win-l/
; As this edits the registry, you need to run the script as Admin
DisableLockWorkstation()
; Set Win+Shift+L to lock screen instead
+#l::LockScreen()
; Enable normal locking again if the script exits
OnExit ExitFunc
SelectWindow(pos) {
thisHwnd := WinExist("A")
WinGetPos(&x, &y, &w, &h, thisHwnd)
if pos == "left" || pos == "right"
center := (x + w) / 2
else
center := (y + h) / 2
minDistance := 9999
targetHwnd := 0
for hwnd in WinGetList() {
if hwnd == thisHwnd
continue
; skip disabled or invisible window and only use windows with a border
style := WinGetStyle(hwnd)
title := WinGetTitle(hwnd)
state := WinGetMinMax(hwnd)
if !(style & styles["WS_BORDER"]) || !(style & styles["WS_VISIBLE"]) || (style & styles["WS_DISABLED"]) || (state == -1)
continue
WinGetPos(&ox, &oy, &ow, &oh, hwnd)
if pos == "left"
distance := center - (ox + ow) / 2
else if pos == "right"
distance := (ox + ow) / 2 - center
else if pos == "up"
distance := center - (oy + oh) / 2
else
distance := (oy + oh) / 2 - center
if 0 < distance && distance < minDistance {
targetHwnd := hwnd
minDistance := distance
}
}
if targetHwnd
WinActivate(targetHwnd)
}
DisableLockWorkstation() {
RegWrite 1, "REG_DWORD", "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System", "DisableLockWorkstation"
}
EnableLockWorkstation() {
RegWrite 0, "REG_DWORD", "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System", "DisableLockWorkstation"
}
LockScreen() {
EnableLockWorkstation()
DllCall("LockWorkStation")
sleep 1000
DisableLockWorkstation()
}
ExitFunc(ExitReason, ExitCode) {
EnableLockWorkstation()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment