February 3, 2021

AutoHotkey: How to store settings (Registry)

When coding in AutoHotkey you want sometimes to store some settings persistently, means that they will be remembered after a script or PC restart.
There are two common approaches for this: one using an Ini file, the other using the registry.
I highlight here how to do this efficiently via the registry.

Access Registry

You can easily access the Registry in AutoHotkey using the RegRead and RegWrite functions.
Have a look at the AutoHotkey documentation to learn how these functions work. Below I show an example.

Helper functions Set and Get Setting

Since I am doing this quite a lot within my PowerTools I have defined 2 functions in the common PowerTools Library:

; ----------------------------------------------------------------------
PowerTools_GetSetting(SettingName){
RegRead, Setting, HKEY_CURRENT_USER\Software\PowerTools, %SettingName%
If (Setting=""){
    Setting := PowerTools_SetSetting(SettingName)
}
return Setting
} ; eofun
; ----------------------------------------------------------------------
PowerTools_SetSetting(SettingName){
; for call from Menu with Name Set <Setting>
SettingName := RegExReplace(SettingName,"^Set ","") 
SettingProp := RegExReplace(SettingName," ","") ; Remove spaces 

RegRead, Setting, HKEY_CURRENT_USER\Software\PowerTools, %SettingProp%
InputBox, Setting, PowerTools Setting, Enter %SettingName%,, 250, 125
If ErrorLevel
    return
PowerTools_RegWrite(SettingProp,Setting)
return Setting
} ; eofun

Now if I want to get a setting and at the same time ask the user to set it if not yet defined, I simply use this piece of code:

Setting := PowerTools_GetSetting("SettingProp")
If (Setting="") ; cancelled
    return

Add Menu to Set the Setting

To let the user change this setting, I add a menu in my AHK Script main Settings menu.
You can even use PowerTools_SetSetting as Menu callback: it will remove "Set " and the spaces in the Menu Name to access the underlying key.
For example:
Menu, SubMenuSettings, Add, Set Phone Number, PowerTools_SetSetting

will access the PhoneNumber registry key. 
Of course, if you want a custom input box and a link to some documentation, you will need to customize the menu callback function. But for a quick implementation, most of the time, it will do.

A variant of previous implementation, with a Ctrl-click action that would open the related help/ documentation page, looks like this:
Menu, SubMenuSettings, Add, Phone Number, SetPhoneNumber

; ----------------------------------------------------------------------
SetPhoneNumer(ItemName){
If GetKeyState("Ctrl") {
    sUrl := "https://helpurl"
    Run, "%sUrl%"
    return
}
PowerTools_SetSetting(ItemName)
}

See also

No comments:

Post a Comment