Skip to content

Instantly share code, notes, and snippets.

@christianrondeau
Last active May 11, 2023 19:50
Show Gist options
  • Save christianrondeau/00d7cd5848f33e029f00ce2b6b935ab9 to your computer and use it in GitHub Desktop.
Save christianrondeau/00d7cd5848f33e029f00ce2b6b935ab9 to your computer and use it in GitHub Desktop.
Automatic keyboard layout change on window focus using AutoHotkey
; How to use:
; 1. Install AuthotKey: https://www.autohotkey.com
; 2. Save this script in `My Documents`
; 3. Create a shortcut in the Startup folder (`Win`+`R`, `shell:startup`)
; 4. Change the configurations below
; 5. Start and test the script!
; Configuration
; Cultures can be fetched from here: https://msdn.microsoft.com/en-us/library/windows/desktop/dd318693(v=vs.85).aspx
; They must be set twice in the language ID;
; en-US: 0x04090409
; fr-CA: 0x0C0C0C0C
global DefaultLanguage := "fr-CA"
global DefaultLanguageIndentifier := "0x0C0C0C0C"
global SecondaryLanguage := "en-US"
global SecondaryLanguageIndentifier := "0x04090409"
global SecondaryLanguageWindowTitles := "VIM,Visual Studio,PowerShell,cmd.exe,ConEmu"
; And the code itself (you should not have to change this)
Gui +LastFound
hWnd := WinExist()
DllCall( "RegisterShellHookWindow", UInt,Hwnd )
MsgNum := DllCall( "RegisterWindowMessage", Str,"SHELLHOOK" )
OnMessage( MsgNum, "ShellMessage" )
Return
ShellMessage( wParam,lParam )
{
WinGetTitle, title, ahk_id %lParam%
; 4 is HSHELL_WINDOWACTIVATED, 32772 is HSHELL_RUDEAPPACTIVATED
If (wParam=4 || wParam=32772) {
If title contains %SecondaryLanguageWindowTitles%
SetKeyboard( title, SecondaryLanguage )
Else
SetKeyboard( title, DefaultLanguage )
}
}
SetKeyboard( title, culture )
{
; 0x50 is WM_INPUTLANGCHANGEREQUEST.
Try
{
If (culture = SecondaryLanguage)
{
PostMessage, 0x50, 0, %SecondaryLanguageIndentifier%,, A
; To debug:
; ToolTip, Using secondary language %SecondaryLanguage%
; Sleep 1000
; ToolTip
}
Else If (culture = DefaultLanguage)
{
PostMessage, 0x50, 0, %DefaultLanguageIndentifier%,, A
; To debug:
; ToolTip, Using default language %DefaultLanguage%
; Sleep 1000
; ToolTip
}
Else
{
; To debug:
; ToolTip, Unknown culture: %culture%
; Sleep 1000
; ToolTip
}
}
Catch e
{
ToolTip, Could not switch to %culture%`n%e%
Sleep 1000
ToolTip
}
}
@christianrondeau
Copy link
Author

And I'm overwhelmed by projects and life :) Sorry, you'll need to figure this one out. <3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment