Reload Autohotkey Script when Modified

I just made an update to reload Autohotkey script when modified. There are a few ways to do this.

When I am editing a script directly I use these hotkey functions:


Send ^s    ;save this file (this assumes your editing this file when you press it though
; TODO: NEEDS FIXING! <-why? most likely will have it open if editing

Sleep 1000 ; If successful, the reload will close this instance during the Sleep, so the line below will never be reached.
MsgBox, 4,, The script could not be reloaded. Would you like to open it for editing?
IfMsgBox, Yes, Edit

;This opens this script in the editor

Pretty simple stuff, and has worked well for me unchanged. However, my scripts start with windows, and I have started keeping my autohotkey scripts in my DropBox folder, so as to sync across all my machines. If, for example, two machines are running and I update the script on one machine, the other machine will get an updated script via DropBox but will still be executing the older version of it. My Solution…

Reload Autohotkey Script when Modified

From trial and error I have found that the following functions need to be at the top of your script.

;; Next two functions are for running a persistent loop to check if this script has
;; been updated since starting. This is useful if updated by DropBox for example.
;; You may want to disable this if doing a lot of editing on this file though.

ThisFileAge := 666 ;set up a global to store file mod date (error 666)
FileGetTime, ThisFileAge, %A_ScriptFullPath%
SetTimer, CheckScriptUpdate, 60000 ;check every 10 minutes

;This function checks the modification date and reloads if necessary
FileGetTime, tempFileAge, %A_ScriptFullPath%
if tempFileAge > %ThisFileAge%
    ;reload the file as it has been updated somewhere (probably by DropBox)
    Sleep 1000 ; If successful, reload closes this instance during 'Sleep', so the line below will never be reached.
    MsgBox, 4,, The script could not be reloaded. Would you like to open it for editing?
    IfMsgBox, Yes, Edit

This works well so far. The first part does not need to be invoked manually, gets the running script’s current age and sets up a timer to automatically call ‘CheckScriptUpdate’ every 10 minutes. The second part, function ‘CheckScriptUpdate’, checks if the script has been modified since it began running and Reloads if necessary.

Leave a Reply