Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Create AutoHotkey Hotkey to Function/Subroutine

The AutoHotkey command Hotkey allows for the creation of dynamic hotkeys at runtime, but its syntax and documentation seems to limit it to built-in or existing labels/subroutines, which makes it much less useful:

Hotkey, KeyName [, Label, Options]

Is there a way to get it to work like regular, hard-coded hotkeys? For example:

#z::MsgBox foobar        ; Typical, hard-coded hotkey pops up a message-box

Hotkey, z, MsgBox foobar ; Nope; complains about missing label “MsgBox foobar”

It looks like it might be possible due to the following line from the manual, however it is not clear how it would work:

Label - Both normal labels and hotkey/hotstring labels can be used.

like image 582
Synetech Avatar asked Oct 12 '12 03:10

Synetech


1 Answers

This is a refinement of FakeRainBrigand's answer. It is used exactly the same:

Hotkey("x", "Foo", "Bar") ; this defines:  x:: Foo("Bar")

Changes from the original:

  1. Prevent accidental auto-execute of the handler subroutine by tucking it into the function.

  2. Allowing me to reduce namespace pollution by narrowing the scope of the hotkeys variable from global to static.

  3. Optimizations: fun is looked up only once (using Func()) at hotkey definition time; At invocation time, object lookups reduced four to two by splitting hotkeys into two objects funs and args;

This still relies of course on the _L version of AutoHotKey because of Object notation and variadic arg* syntax.

Hotkey(hk, fun, arg*) {
    Static funs := {}, args := {}
    funs[hk] := Func(fun), args[hk] := arg
    Hotkey, %hk%, Hotkey_Handle
    Return
Hotkey_Handle:
    funs[A_ThisHotkey].(args[A_ThisHotkey]*)
    Return
}
like image 82
ekipan Avatar answered Oct 22 '22 16:10

ekipan