Use the #If directive in AutoHotkey to conditionally enable or disable hotkeys based on a global boolean variable. Toggle this variable with a dedicated "master" hotkey, such as F12, which switches between including and excluding specific scripts from your current running script without needing to restart the application.
The Problem with Unconditional Hotkeys
When you write an AutoHotkey script, hotkeys defined at the top level are active immediately upon loading. This creates a rigid environment where every key combination is always listening for input. While this works for simple automation, it becomes problematic when you need to selectively activate certain macros while keeping others dormant. For instance, imagine you have a script that remaps your mouse buttons for gaming but also includes text expansion shortcuts for coding. You might want to use the text expansions during work hours but disable them entirely while playing a game to prevent accidental triggers. Without a dynamic solution, you would have to manually comment out lines of code and reload the script every time your context changed. This interrupts workflow and increases the likelihood of errors. The core issue is that standard hotkey definitions lack scope. They do not check the state of the user's intent before executing. By introducing a conditional layer, we can separate the definition of the action from the permission to perform it. This allows a single script file to manage multiple modes of operation seamlessly.Implementing Conditional Hotkeys with #If
The most robust way to handle this in AutoHotkey v1 is using the#If directive. This command evaluates an expression and only makes the subsequent hotkeys active if that expression returns true. When the expression becomes false, those hotkeys become inactive until the condition changes again.
To implement this, you first need a global variable that acts as the switch. Declare this variable at the very top of your script so it is accessible to all sections. A common convention is to name it something descriptive like ScriptsEnabled or ActiveMode. Initialize it to 1 (true) by default, meaning all scripts are included initially.
Next, create a toggle hotkey. This key will be responsible for changing the value of your global variable. It should be a key that you rarely use or one that is easy to reach, such as F12 or Ctrl+Shift+S. Inside this hotkey's subroutine, use the logical NOT operator (!) to invert the boolean value.
; Global variable to control script inclusion
ScriptsEnabled := 1
; Master toggle hotkey
F12::
ScriptsEnabled := !ScriptsEnabled
MsgBox, Scripts are now % (ScriptsEnabled ? "Enabled" : "Disabled")
return
Once the toggle is established, you can wrap your specific script actions in #If blocks. Place the directive immediately before the hotkeys you wish to control. The syntax requires the directive followed by the variable name.
#If ScriptsEnabled
^!t::
; This text expansion only runs if ScriptsEnabled is true
SendInput, Hello World
return
#If
^!t::
; This fallback hotkey runs when ScriptsEnabled is false
Run, notepad.exe
return
In this example, the first block defines Ctrl+Alt+T to send text. The second block defines the same combination to open Notepad. Because of the #If directives, AutoHotkey checks the state of ScriptsEnabled before deciding which routine to execute. If the variable is 1, the text expansion runs. If it is 0, the Notepad command runs instead. This effectively excludes the original script behavior and includes an alternative one.
Handling Multiple Script Groups
You may have different groups of scripts that need independent control. For example, you might want to toggle "Coding Macros" separately from "Gaming Keys." To achieve this, declare multiple boolean variables, such asCodingMode and GamingMode.
Create separate toggle hotkeys for each group. Then, apply the #If directive to each set of hotkeys individually.
CodingMode := 1
GamingMode := 1
F10:: CodingMode := !CodingMode
F11:: GamingMode := !GamingMode
#If CodingMode
^c::
SendInput, Copying text...
return
#If
#If GamingMode
~LButton::
SendInput, Click detected
return
#If
This approach scales well. You can add as many modes as needed by adding new variables and corresponding #If blocks. Each block operates independently, giving you granular control over which parts of your script are active at any given moment.
Best Practices for Maintenance
Maintaining a script with many conditional blocks requires organization. Use comments to clearly mark the start and end of each#If section. This helps other developers (or your future self) understand why a hotkey behaves differently under various conditions.
Avoid nesting #If directives too deeply. While AutoHotkey supports nested conditions, complex logic can become hard to debug. If you find yourself writing intricate expressions inside #If, consider simplifying the logic by combining variables into a single mode string or using functions to return the active state.
Also, be aware that #If affects hotkeys defined below it in the script. Hotkeys defined above the directive remain unaffected unless they are also wrapped in their own #If block. Always test your toggle keys thoroughly to ensure they update the state correctly across all relevant sections.
How to assign Appskey & AltGr ( LCtrl & RAlt ) as a Hotkey in AHK? demonstrates how to handle complex modifier combinations, which can be useful if you need more unique toggle keys that don't conflict with existing system shortcuts.
Frequently Asked Questions
Can I use #If in AutoHotkey v2?
Yes, but the syntax has changed slightly. In v2, you use theHotkey object to dynamically enable or disable keys rather than relying solely on the #If directive. You can still use conditional logic within the hotkey function itself, but the structural approach differs from v1.
What happens if I press the toggle key while a script is running?
The global variable updates immediately, affecting only future executions of the controlled hotkeys. Any currently running subroutine will continue to completion regardless of the toggle state. This ensures that mid-action commands do not abort unexpectedly.Can I exclude just one line of code instead of a whole hotkey?
No,#If controls hotkey activation, not individual lines of code. To exclude specific logic, you must wrap the code inside the hotkey's subroutine in an If statement that checks your global variable. This gives you fine-grained control within a single hotkey.
Why doesn't my toggle key work after reloading the script?
Ensure that your toggle hotkey is defined outside of any#If block that depends on the variable it modifies. If the toggle key itself is conditional on the variable, it will be disabled when the variable is false, creating a deadlock where you cannot re-enable the scripts.
Is there a performance impact using many #If directives?
The performance impact is negligible. AutoHotkey evaluates the#If condition only when you attempt to trigger a hotkey. There is no background processing overhead for inactive keys. However, excessive nesting can make the script harder to read and maintain.