AutoHotKey – Focus on Window After Running Actions

autohotkeyhotkeys

I use AHK 1.1 to set the capslock to be a hotkey to toogle ArtRage full screen mode (workbench mode), I do so, because ArtRage doesn't allow me to set CapsLock as a hotkey, but I'm quite used to use that key to do that in many programs, so I thought AHK could help me.

I tried this and it worked:

;   AR4 Toggle Workbench Mode
If WinActive("ahk_class ArtRage 3")

Capslock::
Sleep 20
Send {SC037 Down}   ;   NumpadMult
Sleep 10
Send {SC037 Up} ;   NumpadMult
Sleep 90
WinActivate, ahk_class ArtRage 3
return

#If

So the script works fine, but then somehow ArtRage window loses focus, I mean I still see the ArtRage window, but I noticed that it loses focus, because if I want to run another AHK hotkey (that runs only #If WinActive("ahk_class ArtRage 3") ) immediately after the script above is done, it will not detect ArtRage window as open, so it will not run, unless I manually click ArtRage window.

I tried to focus again after the Capslock (toggle Workbench Mode) is done, but WinActivate, ahk_class ArtRage 3 doesn't refocus on ArtRage window, isn't there another way to refocus on a window in AHK?

EDITED >>>
how can I place a IfWinExist("ahk_class ArtRage 3") at the end of a piece of actions? cuz I can't just run it on top of my AHK script cuz it would always focus on ArtRage, even if I'm working in other apps right?, I tried this but it is not in a proper syntax, could you please post an example??

#If WinActive("ahk_class ArtRage 3")

Capslock::
Send {SC037 Down}   ;   NumpadMult
Sleep 30
Send {SC037 Up} ;   NumpadMult
Sleep 30
IfWinExist("ahk_class ArtRage 3")
    WinActivate, ahk_class ArtRage 3
return

#If

Best Answer

Try this (first of all as standalone script):

;   AR4 Toggle Workbench Mode
#If WinActive("ahk_class ArtRage 3")

    Capslock::
    KeyWait, Capslock   ;  wait until Capslock is released 
    Sleep 20
    Send {NumpadMult}
    Sleep 90
    If !WinActive("ahk_class ArtRage 3")  ;  means: IfWinNotActive
    {
        Loop
        {           
            ;  Which window becomes active in this case?
            WinGetTitle, ActiveTitle, A
            WinGetClass, ActiveClass, A
            ToolTip, Active Window:`n%ActiveTitle%  ahk_class %ActiveClass%
            WinActivate, ahk_class ArtRage 3
            Sleep 50
            If WinActive("ahk_class ArtRage 3")
            {
                ToolTip
                break
            }                   
        }
    }
    return

#If

Esc:: ExitApp
Related Question