Creates context-sensitive hotkeys and hotstrings. Such hotkeys perform a different action (or none at all) depending on the result of an expression.
#If [, Expression ]
| Expression | Any valid expression. |
Any valid expression may be used to define the context in which a hotkey should be active. For example:
#If WinActive("ahk_class Notepad") or WinActive(MyWindowTitle)
#Space::MsgBox You pressed Win+Spacebar in Notepad or %MyWindowTitle%.
Like the #IfWin directives, #If is positional: it affects all hotkeys and hotstrings physically beneath it in the script. #If and #IfWin are also mutually exclusive; that is, only the most recent #If or #IfWin will be in effect.
To turn off context sensitivity, specify #If or any #IfWin directive but omit all the parameters. For example:
#If
When the key combination which forms a hotkey is pressed, the #If expression is evaluated to determine if the hotkey should activate. The system may not respond to keyboard input until expression evaluation completes or times out.
Due to a design quirk of AutoHotkey, #If expressions may be evaluated twice under certain circumstances. For this reason, #If expressions should be designed to have no side-effects.
Most behavioural properties of the #IfWin directives also apply to #If.
#IfTimeout may be used to override the default timeout value.
To create context-sensitive hotkeys with the Hotkey command, select an existing #If expression with Hotkey, If, Expression. Expression must exactly match the text of an existing #If expression, excluding "#If". The comma following "If" is required. See Example 4 below.
; Example 1: Adjust volume by scrolling the mouse wheel over the taskbar.
#If MouseIsOver("ahk_class Shell_TrayWnd")
WheelUp::Send {Volume_Up}
WheelDown::Send {Volume_Down}
MouseIsOver(WinTitle) {
MouseGetPos,,, Win
return WinExist(WinTitle . " ahk_id " . Win)
}
; Example 2: Simple word-delete shortcuts for all Edit controls.
#If ActiveControlIsOfClass("Edit")
^BS::Send ^+{Left}{Del}
^Del::Send ^+{Right}{Del}
ActiveControlIsOfClass(Class) {
ControlGetFocus, FocusedControl, A
ControlGet, FocusedControlHwnd, Hwnd,, %FocusedControl%, A
WinGetClass, FocusedControlClass, ahk_id %FocusedControlHwnd%
return (FocusedControlClass=Class)
}
; Example 3: Context-insensitive hotkey.
#If
Esc::ExitApp
; Example 4: Dynamic hotkeys.
NumpadAdd::
Hotkey, If, MouseIsOver("ahk_class Shell_TrayWnd")
if (doubleup := !doubleup)
Hotkey, WheelUp, DoubleUp
else
Hotkey, WheelUp, WheelUp
return
DoubleUp:
Send {Volume_Up 2}
return