Graham
Graham

Reputation: 8141

How to have one key toggle between two functions using AHK

How would I go about creating a hotkey in AHK that runs one function the first time it is pressed and another one the second time it is pressed. I'm trying to emulate an on/off scenario.

Can it be done and if so how?

Something like this pseudo code is what I'm looking for:

#space::toggleit()

toggleit()
{
   if (last time it was pressed, functionA was run)
      run functionB
   else
      run functionA
}

I'm using AHK version 1.1.19.01

Upvotes: 0

Views: 3934

Answers (3)

Graham
Graham

Reputation: 8141

I found a solution. Putting it here for other's benefit:

#space::tog()

tog()
{
    static togstate = 0
    if (togstate = 1)
    {
        msgbox ON
        togstate = 0
    }
    else
    {
        msgbox OFF
        togstate = 1
    }
}

Upvotes: 1

Dennis_E
Dennis_E

Reputation: 8894

An easy way is to use a variable:

setting := false
toggleit()
{
   if setting
      run functionB
   else
      run functionA
   setting := !setting
}

Upvotes: 0

phil294
phil294

Reputation: 10822

Try using AutoHotkey's hotkey-command:

hotkey, #space, functionA
return

functionA:
hotkey, #space, functionB
msgbox, A
return

functionB:
hotkey, #space, functionA
msgbox, B
return

If you'd want to toggle only between functionA and "do nothing", you can use the following:

hotkey, #space, functionA, toggle
return

functionA:
msgbox, A
return

Upvotes: 2

Related Questions