February 5, 2021

AutoHotkey: How to add a Setting for a user-configurable hotkey

In this post I explain how you can offer the option to your user to set a custom hotkey for your AutoHotkey script. This option is configurable via a AHK Icon Tray Settings menu.
I illustrate this on a example, the Mute PowerTool.

Example code is available here: Mute.ahk

Step-by-step

Store the Setting

To have the setting stick with the script (e.g. after a PC restart) you need to store it somewhere.
Two main approaches are possible for this: use a ini file or user a registry key.
For this case, I would rather go for using a registry key. See detailed post explaining this part here.

Settings Menu to Set the Hotkey

Menu, SubMenuSettings, Add, &Mute Hotkey, Mute_HotkeySet

The first time you load the screen, you shall activate the Hotkey.

RegRead, MuteHotkey, HKEY_CURRENT_USER\Software\PowerTools, MuteHotkey
If (MuteHotkey != "") {
    Mute_HotkeyActivate(MuteHotkey)
}

GUI to enter the Hotkey

I recommend/ am using this script HotkeyGUI (AHK forum source - credit to jballi) (It is also available in my GitHub here ahk/Lib/HotkeyGUI.ahk)

Activate the Hotkey

Once the hotkey textual definition is available you need to activate the Hotkey.
This is done with the use of the Hotkey function.
When changing it, you need to deactivate the former one.

Mind to avoid self-referencing hotkeys using the $ symbol.

Mute_HotkeySet(){

RegRead, MuteHotkey, HKEY_CURRENT_USER\Software\PowerTools, MuteHotkey
HK := HotkeyGUI(,MuteHotkey,,," Mute - Set Global Hotkey")

If ErrorLevel ; Cancelled
  return
If (HK = MuteHotkey) ; no change
  return
PowerTools_RegWrite("MuteHotkey",HK)

If (HK = "") { ; reset/ disable hotkey
    ;Turn off the new hotkey.
    Hotkey, %MuteHotkey%, MuteHotkeyCb, Off 
    TrayTipAutoHide("Mute Hotkey","Mute Hotkey is now Off!",1000)
    return
}

; Turn off the old Hotkey
If Not (MuteHotkey == "")
    Hotkey, %MuteHotkey%, MuteHotkeyCb, Off

; Activate new hotkey
Mute_HotkeyActivate(HK)
} ; eofun
; ----------------------------------------------------------------------

Mute_HotkeyActivate(HK) {
;Turn on the new hotkey.
Hotkey, IfWinActive, ; for all windows/ global hotkey
Hotkey, %HK%, MuteHotkeyCb, On ; use $ to avoid self-referring hotkey if Ctrl+Shift+M is used
TipText = Mute Hotkey set to %HK%
TrayTipAutoHide("Mute Hotkey On",TipText,2000)
} ; eofun

Screencast

See also

AutoHotkey: How to store settings via the registry

Hotkey - Syntax & Usage | AutoHotkey



No comments:

Post a Comment