Fred
Fred

Reputation: 13

AHK if statement - run instruction based on key combination pressed

Is there a way to combine the below common instructions into one set of code? i.e. if ctrl-m was pressed then type minutes or else if ctrl-s was pressed type seconds.

Would appreciate your help.

^m::
WinActivate menu
Click, 100, 50
sleep 200
Send minutes; typing into input field
sleep 200
Click, 100, 100; clicking button opens application called minutes
return

^s::
WinActivate menu
Click, 100, 50
sleep 200
Send seconds; typing into input field
sleep 200
Click, 100, 100; clicking button opens application called seconds
return

Upvotes: 0

Views: 851

Answers (1)

0x464e
0x464e

Reputation: 6489

You can define multiple different hotkeys to run the same block of code and then you can tell which hotkey was used by checking A_ThisHotkey.

^m::
^s::
    if(A_ThisHotkey = "^m")
        variable := "minutes"
    else
        variable := "seconds"
    WinActivate, menu
    Click, 100, 50
    Sleep, 200
    SendInput, % variable ;typing into input field
    Sleep, 200
    Click, 100, 100 ;clicking button opens application called minutes
return

Note that we're checking the value of A_ThisHotkey as soon as possible, so we're sure to get the value of the correct hotkey, and not some other hotkey which could've interrupted the current thread (as recommended in the documentation).
Also switched over to SendInput due to it being faster and more reliable.


As a bonus, if you want more compact code, replace the if-else statement with a ternary:

variable := A_ThisHotkey = "^m" ? "minutes" : "seconds"

Upvotes: 1

Related Questions