Thursday, November 1, 2018

Toggle Keyboard Layout in Windows with AutoHotkey

Run AHK script and press Super+1 to switch keyboard layouts.


#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn  ; Enable warnings to assist with detecting common errors.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.
; This should be replaced by whatever your native language is. See
; http://msdn.microsoft.com/en-us/library/dd318693%28v=vs.85%29.aspx
; for the language identifiers list.
de := DllCall("LoadKeyboardLayout", "Str", "00010407", "Int", 1)
en := DllCall("LoadKeyboardLayout", "Str", "00010409", "Int", 1)
ro := DllCall("LoadKeyboardLayout", "Str", "00010418", "Int", 1)

#1::
w := DllCall("GetForegroundWindow")
pid := DllCall("GetWindowThreadProcessId", "UInt", w, "Ptr", 0)
l := DllCall("GetKeyboardLayout", "UInt", pid)
if (l = en)
{
PostMessage 0x50, 0, %ro%,, A
}
else if (l = de)
{
PostMessage 0x50, 0, %en%,, A
}
else
{
PostMessage 0x50, 0, %de%,, A
}