Search code examples
keyboard-shortcutsautohotkey

How to chain sequence of Hotkeys in Autohotkey?


I've been searching for the last hour here and in ahk's forum with no success, although I am sure this has been done and asked already somewhere. Maybe I am using the wrong terminology but, here goes the question:

I would like to create a few shorcuts sequences such that pressing a key combination as ^k (ctrl+k) enters a state where I have 1 second to press another key and get different results for each key. Preferably, it would work by pressing and holding ctrl and then k and then {a or b} while still holding k. And if I press ctrl+k and release, it sends ctrl+k to the application in focus, as usual.

^k then a::does something (with ctrl pressed down)
^k then b::does something else (with ctrl pressed down)
^k alone::sends ^k as usual

For those that use sublime, the behaviour I am after is the same as ctrl + k then b toggles the side bar. (I am sure other editors have similar behaviour)

I appreciate your attention and time.


Solution

  • I'm going to have to be blunt now and just say it, the code in the accepted answer is going to give me nightmares. It's truly terrible.

    Here's how it actually should be done:

    ^k::return
    
    #If, A_PriorHotkey = "^k"
    ^a::ToolTip, % A_ThisHotkey " pressed with ^k"
    ^b::ToolTip, % A_ThisHotkey " pressed with ^k"
    ^c::ToolTip, % A_ThisHotkey " pressed with ^k"
    ^d::ToolTip, % A_ThisHotkey " pressed with ^k"
    
    ^k up::SendInput, ^k
    #If
    

    Very conveniently done by creating context sensitive hotkeys and just checking what the previous hotkey was.

    Should be quite simple and straight forward, but here's a explanation for it anyway:
    First just create an empty hotkey for Ctrl + K to consume any presses to it and set A_PriorHotkey.
    Then create the context sensitive hotkeys, if Ctrl + K is still held down, it's going to be the previous hotkey. Otherwise its release, ^k up, will be the previous hotkey.

    This will work as asked, except for that 1 second window you described. I don't really get it. What is its purpose supposed to be? Sounded very useless to me, since k is going to need to be held down anyway. Would make sense if k could be released mid way.

    If the 1 second window is somehow useful/needed, then will have to add a A_TickCount check in there. It wont complicate it too much more.