Dynamically create AutoHotkey hotkeys for a function / subroutine

The AutoHotkey Hotkey allows you to create dynamic hot keys at run time, but its syntax and documentation seem to limit it to built-in or existing labels / routines, which makes it much less useful:

Hotkey, KeyName [, Label, Options]

Is there a way to make it work like regular hardcoded hotkeys? For instance:

 #z::MsgBox foobar ; Typical, hard-coded hotkey pops up a message-box Hotkey, z, MsgBox foobar ; Nope; complains about missing label "MsgBox foobar" 

This seems to be possible due to the following line from the manual, however it is unclear how this will work:

Label. You can use both regular shortcuts and hotkey / hotkey labels.

+6
source share
3 answers

Doing exactly what you want is not possible in AutoHotkey. This is the closest way I can think of.

Call this file Hotkeys.ahk and put it in My Documents/AutoHotkey/Lib . Alternatively, create a folder named Lib and put it in the same directory as your main script.

 Hotkeys := {} Hotkey(hk, fun, p*) { global hotkeys hotkeys[hk] := {} hotkeys[hk].fun := fun hotkeys[hk].p := p Hotkey, %hk%, HandleHotkey } HandleHotkey: hotkeys[A_ThisHotkey].fun(hotkeys[A_ThisHotkey].p*) return 

Here is an example script with which you could use it.

 Hotkey("e", "msgbox", "foobar") MsgBox(msg) { msgbox % msg } #Include <Hotkeys> 

The first parameter is the hotkey, the second is the function to call, and after that everything is passed to the function.

+7
source

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

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

Changes from the original:

  • Prevent accidental automatic launch of a handler routine by placing it in a function.

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

  • Optimization : fun viewed only once (using Func() ) at the time of definition of hotkey; During the call, the search for objects is reduced from four to two by splitting hotkeys into two objects funs and args ;

It still, of course, depends on the _L version of AutoHotKey due to the Object notation and the arg* syntax arg* .

 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 } 
+6
source

Is this what you are looking for?

 #Persistent #SingleInstance Force #installKeybdHook Hotkey, #z, MyLabel MyLabel: MsgBox,OK Return 
0
source

Source: https://habr.com/ru/post/927524/


All Articles