Search code examples
autohotkey

Autohotkey - Limit to only one hotkey execution at a time


I want to write an Autohotkey script that lets me press the keyboard keys fghjkl, with each translating to a left mouse-click. However I do NOT want them to be able to be all clicked at the same time (and thus counting as 6 mouseclicks), but only always one at a time.

I tried to achieve this by adding a small sleep period to each, but all this achieved was that I was able to press all at the same time, with the sleep duration stacking up...

How can I achieve what I need?

My current code is as follows:

f::
g::
h::
j::
k::
l::{
    SendInput "{LButton}"
    KeyWait "f"
    KeyWait "g"
    KeyWait "h"
    KeyWait "j"
    KeyWait "k"
    KeyWait "l"
}

Solution

  • AHK v2: (Exact same code works in v1 as well with a tiny syntax change HotIf -> If)

    You can utilize context sensitive hotkeys:

    #HotIf !A_PriorHotkey || (A_PriorHotkey ~= "f|g|h|j|k|l" && A_TimeSincePriorHotkey > 500)
    f::
    g::
    h::
    j::
    k::
    l::Click
    #HotIf
    

    Breakdown:
    !A_PriorHotkey || (A_PriorHotkey ~= "f|g|h|j|k|l" && A_TimeSincePriorHotkey > 500)

    • !A_PriorHotkey
      • If there is no prior hotkey (no hotkey has been pressed yet after this script was started)
    • A_PriorHotkey ~= "f|g|h|j|k|l"
      • Check if the prior hotkey is F, G, H, J, K, or L
      • Utilizes RegExMatch shorthand(docs)
    • A_TimeSincePriorHotkey > 500
      • If at least 500ms has passed since the prior hotkey was pressed (i.e. a click)