5
votes

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?

2

2 Answers

4
votes

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"
}
1
votes

This is how I've done it:

#If WinActive("AHK.ahk - Notepad") or WinActive("*AHK.ahk - Notepad")
    ~^s::
        Reload
    Return
#If

Checks if the current window is the script that I want autoreloaded whenever I hit Ctrl-S. The ~ means the default action of Ctrl-S (saving the file) is preserved, and then we simply reload it.