Search code examples
autohotkey

[AutoHotKey]How to auto switch keyboard to English through AutoHotKey when open Battlefield2042?


As far as I know, Battlefield2042 windows name is ahk_exe BF2042.exe

And the code to change to English is SendMessage, 0x50, 0x0409, 0,, A

Now the question is how to let it work?

I've tried

#IfWinActive, ahk_exe BF2042.exe
{
   Lang := 0x0409
   SendMessage, 0x50, Lang, 0,, A
}
#If

It seems not working.

My whole script is

; Some configs when playing games
#If WinActive("ahk_exe r5apex.exe") or WinActive("ahk_exe Overwatch.exe") or WinActive("ahk_exe bfv.exe") or WinActive("ahk_exe Prospect-Win64-Shipping.exe") or WinActive("ahk_exe VALORANT-Win64-Shipping.exe") or WinActive("ahk_exe Titanfall2.exe") or WinActive("ahk_exe BF2042.exe")
{
    !Tab::Return

    #Tab::Return

    LWin::Return

    RWin::Return

    Delete::Home

    $!esc::return
    
    F12::!esc
}
#If

; Switch keyboard using CapsLock
AltState = 0
CapsLock::
    if AltState = 2
    {
        SetCapsLockState, % GetKeyState("CapsLock","T") ? "Off" : "On"
    }
    else
    {
        KeyWait, CapsLock, T0.3
        If ErrorLevel
        {
            SetCapsLockState, % GetKeyState("CapsLock","T") ? "Off" : "On"
                KeyWait, CapsLock
        }
        else
        {
            SetCapsLockState, % "Off"
            SendInput {LCtrl down}{Space}{LCtrl up}
        }
    }
Return

Please help me to integrate the function into my script.


Solution

  • You need a timer or a loop to perform an action, each time a window appears or becomes active.

    #NoEnv
    #SingleInstance Force
    
    Lang := 0x0409 ; English 
    
    AltState = 0
    
    SetTimer, switch_keyboard, 500
    
                RETURN   ; === end of auto-execute section ===
    
    switch_keyboard:
        If !WinActive("ahk_exe BF2042.exe") ; "!" means "Not" in this case
            return ; do nothing
        ; otherwise:
        SetTimer, switch_keyboard, Off  ; turns the timer off 
        SendMessage, 0x50, Lang, 0,, A  ; change to English 
        WinWaitNotActive, ahk_exe BF2042.exe
        SetTimer, switch_keyboard, On  ; for next time Battlefield2042 becomes active
    return
    
    ; Your hotkeys here