Search code examples
autohotkey

Automatically reload AutoHotkey script when modified


When testing AutoHotkey scripts, I sometimes forget to reload my scripts after making changes. This leads to me accidentally testing old, outdated versions of my scripts.

Instead of manually reloading the script, I would like to have scripts automatically reload if they have been modified.

How can I make AutoHotkey reload the current script any time a .ahk file is modified?


Solution

  • Somewhere near start of the script, in the auto-execute section

    #SingleInstance force
    FileGetTime ScriptStartModTime, %A_ScriptFullPath%
    SetTimer CheckScriptUpdate, 100, 0x7FFFFFFF ; 100 ms, highest priority
    

    Anywhere in the script (usually somewhere at the bottom):

    CheckScriptUpdate() {
        global ScriptStartModTime
        FileGetTime curModTime, %A_ScriptFullPath%
        If (curModTime == ScriptStartModTime)
            return
        SetTimer CheckScriptUpdate, Off
        Loop
        {
            reload
            Sleep 300 ; ms
            MsgBox 0x2, %A_ScriptName%, Reload failed. ; 0x2 = Abort/Retry/Ignore
            IfMsgBox Abort
                ExitApp
            IfMsgBox Ignore
                break
        } ; loops reload on "Retry"
    }