Search code examples
autohotkey

Autohotkey multiple hotkeys mapping to the same function


I have several hotkeys that all do the same things, I have multiples so I can call them wherever my hands happen to be at the time and can be used on multiple keyboards eg:

#]::Send {Media_Next}
XButton2 & RButton::Send {Media_Next}
SC15D & ]::Send {Media_Next}

Is there any way to combine these things onto one line without having to repeat myself all over the place?


Solution

  • Multiple hotkey definitions in one line can't be done, at least not without a genuine hack.
    Still, there are ways to simplify your script:

    Method 1: "Trickling hotkeys"

    This is the simplest and most straight-forward way to assign multiple hotkeys the same functionality. It works by simply writing the hotkeys one below the other, only assigning the last hotkey one or several commands:

    #]::
    XButton2 & RButton::
    SC15D & ]::Send {Media_Next}
    

    Method 2: Dynamic hotkey creation

    Using the Hotkey command, you can assign labels to hotkeys at runtime. This means, they can be used in a loop:

    for i, keyName in ["#]", "XButton2 & RButton", "SC15D & ]"]
        Hotkey, % keyName, SendMediaNext
    
    Exit
    
    SendMediaNext: 
        Send {Media_Next}
    return
    

    Hotkeys created at runtime aren't as performant as hard-coded hotkeys, but in most cases, you won't notice a difference. I would still go with Method 1, since it's more readable.