How to include and exclude specific script from the current running script by hotkeys

Abstract: Resolve conflicts between competing hotkeys by using a global boolean variable and the #If directive to dynamically include or exclude specific script actions.

Created: 2026-08-09 by

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 as CodingMode 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 the Hotkey 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.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More