Hotkey

Creates, modifies, enables, or disables a hotkey while the script is running.

Hotkey KeyName , Callback, Options

Parameters

KeyName

Type: String

Name of the hotkey's activation key, including any modifier symbols. For example, specify #c for the Win+C hotkey.

If KeyName already exists as a hotkey, that hotkey will be updated with the values of the function's other parameters.

KeyName can also be the name of an existing hotkey (created with the double-colon syntax), which will cause that hotkey to be updated with the values of the function's other parameters.

When specifying an existing hotkey, KeyName is not case sensitive. However, the names of keys must be spelled the same as in the existing hotkey (e.g. Esc is not the same as Escape for this purpose). Also, the order of modifier symbols such as ^!+# does not matter. GetKeyName can be used to retrieve the standard spelling of a key name.

When a hotkey is first created -- either by the Hotkey function or the double-colon syntax in the script -- its key name and the ordering of its modifier symbols becomes the permanent name of that hotkey as reflected by A_ThisHotkey and Callback's parameter. This name is shared by all variants of the hotkey, and does not change even if the Hotkey function later accesses the hotkey with a different symbol ordering.

If the hotkey variant already exists, its behavior is updated according to whether KeyName includes or excludes the tilde (~) prefix.

The use hook ($) prefix can be added to existing hotkeys. This prefix affects all variants of the hotkey and cannot be removed.

Callback

Type: String or Object

The subroutine to execute (as a new thread) when the hotkey is pressed. This can be a function name, a function object, or a hotkey name without trailing colons.

If Callback is a function, it is called with one parameter, the name of the hotkey. Hotkeys defined with the double-colon syntax automatically use the parameter name ThisHotkey. Hotkeys can also be assigned a function name without the Hotkey function.

If Callback is a hotkey name, its original function is used; specifically, the original function of the hotkey variant corresponding to the current HotIf criteria. This is usually used to restore a hotkey's original function after having changed it, but can be used to assign the function of a different hotkey, provided that both hotkeys use the same HotIf criteria.

This parameter can be left blank if KeyName already exists as a hotkey, in which case its callback will not be changed. This is useful to change only the hotkey's Options.

Note: If the function is specified but the hotkey is disabled from a previous use of this function, the hotkey will remain disabled. To prevent this, include the word ON in Options.

This parameter can also be one of the following special values:

On: The hotkey becomes enabled. No action is taken if the hotkey is already On.

Off: The hotkey becomes disabled. No action is taken if the hotkey is already Off.

Toggle: The hotkey is set to the opposite state (enabled or disabled).

AltTab (and others): These are special Alt-Tab hotkey actions that are described here.

Options

Type: String

A string of zero or more of the following letters with optional spaces in between. For example: On B0.

On: Enables the hotkey if it is currently disabled.

Off: Disables the hotkey if it is currently enabled. This is typically used to create a hotkey in an initially-disabled state.

B or B0: Specify the letter B to buffer the hotkey as described in #MaxThreadsBuffer. Specify B0 (B with the number 0) to disable this type of buffering.

Pn: Specify the letter P followed by the hotkey's thread priority. If the P option is omitted when creating a hotkey, 0 will be used.

Tn: Specify the letter T followed by a the number of threads to allow for this hotkey as described in #MaxThreadsPerHotkey. For example: T5.

In (InputLevel): Specify the letter I (or i) followed by the hotkey's input level. For example: I1.

If any of the option letters are omitted and the hotkey already exists, those options will not be changed. But if the hotkey does not yet exist -- that is, it is about to be created by this function -- the options will default to those most recently in effect. For example, the instance of #MaxThreadsBuffer that occurs closest to the bottom of the script will be used. If #MaxThreadsBuffer does not appear in the script, its default setting (OFF in this case) will be used.

Error Handling

An exception is thrown if a parameter is invalid or memory allocation fails.

One of the following exceptions may be thrown if the hotkey is invalid or could not be created:

Error Description
"Invalid key name." The KeyName parameter specifies one or more keys that are either not recognized or not supported by the current keyboard layout/language. Exception.Extra contains the key name; e.g. "Entre" from !Entre.
"Unsupported prefix key." For example, using the mouse wheel as a prefix in a hotkey such as WheelDown & Enter is not supported. Exception.Extra contains the prefix key.
"This AltTab hotkey must have exactly one modifier/prefix."
"This AltTab hotkey must specify which key (L or R)."
The KeyName parameter is not suitable for use with the AltTab or ShiftAltTab actions. A combination of two keys is required. For example: RControl & RShift::AltTab. Exception.Extra contains KeyName.
"Nonexistent hotkey." The function attempted to modify a nonexistent hotkey. Exception.Extra contains KeyName.
"Nonexistent hotkey variant (IfWin)." The function attempted to modify a nonexistent variant of an existing hotkey. To solve this, use HotIf to set the criteria to match those of the hotkey to be modified. Exception.Extra contains KeyName.
"Max hotkeys." Creating this hotkey would exceed the limit of 32762 hotkeys per script (however, each hotkey can have an unlimited number of variants, and there is no limit to the number of hotstrings).


Tip: Try-Catch can be used to test for the existence of a hotkey variant.

try
    Hotkey "^!p"
catch
    MsgBox "The hotkey does not exist or it has no variant for the current If criteria."

Remarks

The current HotIf setting determines the variant of a hotkey upon which the Hotkey function will operate.

If the goal is to disable selected hotkeys or hotstrings automatically based on the type of window that is active, Hotkey "^!c", "Off" is usually less convenient than using #HotIf with WinActive/WinExist (or their dynamic counterparts HotIfWinActive/Exist).

Creating hotkeys via the double-colon syntax performs better than using the Hotkey function because the hotkeys can all be enabled as a batch when the script starts (rather than one by one). Therefore, it is best to use this function to create only those hotkeys whose key names are not known until after the script has started running. One such case is when a script's hotkeys for various actions are configurable via an INI file.

If the script is suspended, newly added/enabled hotkeys will also be suspended until the suspension is turned off (unless they are exempt as described in the Suspend section).

The keyboard and/or mouse hooks will be installed or removed if justified by the changes made by this function.

Although the Hotkey function cannot directly enable or disable hotkeys in scripts other than its own, in most cases it can override them by creating or enabling the same hotkeys. Whether this works depends on a combination of factors: 1) Whether the hotkey to be overridden is a hook hotkey in the other script (non-hook hotkeys can always be overridden); 2) The fact that the most recently started script's hotkeys generally take precedence over those in other scripts (therefore, if the script intending to override was started most recently, its override should always succeed); 3) Whether the enabling or creating of this hotkey will newly activate the keyboard or mouse hook (if so, the override will always succeed).

Once a script has at least one hotkey, it becomes persistent, meaning that ExitApp rather than Exit should be used to terminate it.

Variant (Duplicate) Hotkeys

A particular hotkey can be created more than once if each definition has different If criteria. These are known as hotkey variants. For example:

HotIfWinActive "ahk_class Notepad"
Hotkey "^!c", "MyFuncForNotepad"
HotIfWinActive "ahk_class WordPadClass"
Hotkey "^!c", "MyFuncForWordPad"
HotIfWinActive
Hotkey "^!c", "MyFuncForAllOtherWindows"

If more than one variant of a hotkey is eligible to fire, only the one created earliest will fire. The exception to this is the global variant (the one with no If criteria): It always has the lowest precedence, and thus will fire only if no other variant is eligible.

When creating duplicate hotkeys, the order of modifier symbols such as ^!+# does not matter. For example, "^!c" is the same as "!^c". However, keys must be spelled consistently. For example, Esc is not the same as Escape for this purpose (though the case does not matter). Finally, any hotkey with a wildcard prefix (*) is entirely separate from a non-wildcard one; for example, "*F1" and "F1" would each have their own set of variants.

For more information about context-sensitive hotkeys, see #HotIf's General Remarks.

Related

Hotkey Symbols, HotIf, A_ThisHotkey, #MaxThreadsBuffer, #MaxThreadsPerHotkey, Suspend, IsFunc, Threads, Thread, Critical, Return, Menu object, SetTimer

Examples

#1

Hotkey "^!z", "MyFunc"

MyFunc(ThisHotkey)
{
    MsgBox "You pressed " ThisHotkey
}

#2: Other examples

Hotkey "RCtrl & RShift", "AltTab" ; Makes RCtrl & RShift operate like Alt-Tab.
Hotkey "$+#c", "Off"  ; Disables the Shift-Win-C hotkey.
Hotkey "^!a", , "T5"  ; Changes the hotkey to allow 5 threads.

HotIfWinActive "ahk_class Notepad"
Hotkey "^!c", "MyFuncForNotepad"  ; Creates Ctrl-Alt-C as a hotkey that works only in Notepad.

#3: Create Alt+W as a hotkey that works only in Notepad.

HotIfWinActive "ahk_class Notepad"
Hotkey "!w", "ToggleWordWrap"  ; !w = Alt+W

ToggleWordWrap(ThisHotkey)
{
    MenuSelect "A",, "Format", "Word Wrap"
}

#4: This GUI allows you to register primitive three-key combination hotkeys:

HkGui := Gui.New()
HkGui.Add("Text", "xm", "Prefix key:")
HkGui.Add("Edit", "yp x100 w100 vPrefix", "Space")
HkGui.Add("Text", "xm", "Suffix hotkey:")
HkGui.Add("Edit", "yp x100 w100 vSuffix", "f & j")
HkGui.Add("Button", "Default", "Register").OnEvent("Click", "RegisterHotkey")
HkGui.OnEvent("Close", (*) => ExitApp())
HkGui.OnEvent("Escape", (*) => ExitApp())
HkGui.Show()

RegisterHotkey(thisCtrl, *)
{
    Saved := thisCtrl.Gui.Submit(false)
    HotIf (*) => GetKeyState(Saved.Prefix)
    Hotkey Saved.Suffix, (ThisHotkey) => MsgBox(ThisHotkey)
}