AHK: Waiting for Multiple Keys Pressed (Missing VK, not SC)

Abstract: Detect simultaneous key presses in AutoHotkey using VK codes for cross-layout compatibility.

Created: 2026-10-04 by
You can wait for multiple keys to be pressed simultaneously in AutoHotkey by using the GetKey function within a loop or by combining key names with the logical OR operator (||) inside conditional statements. This approach relies on Virtual Key (VK) codes, which are the standard identifiers for most keyboard inputs, allowing you to detect complex combinations without resorting to Scan Code (SC) mappings that vary by hardware.

Understanding Virtual Keys vs. Scan Codes

When scripting keyboard interactions, it is crucial to distinguish between Virtual Key (VK) codes and Scan Code (SC) codes. VK codes are consistent across different keyboard layouts and hardware manufacturers, representing the logical key press (e.g., 'A', 'B', 'Enter'). In contrast, SC codes represent the physical location of the key on the keyboard matrix. For most automation tasks, especially those requiring compatibility across various machines, VK codes are the preferred method because they remain stable regardless of whether you are using a US QWERTY, UK AZERTY, or German QWERTZ layout. The original problem often arises when users attempt to use scan codes for multi-key detection, only to find their scripts failing on different keyboards. By sticking to VK codes, you ensure that your script waits for the intended logical action rather than a specific physical switch position. This distinction simplifies the logic significantly, as you do not need to maintain a mapping table for every possible keyboard variant.

Using GetKey for Simultaneous Detection

The most robust way to wait for multiple keys is to use the GetKey function. This function returns true if the specified key is currently held down. To check for multiple keys, you can chain these checks together. For example, if you want to wait until both the Shift key and the Z key are pressed, you would structure your condition to evaluate both states.
WaitForKeys() {
    while (!GetKey("Shift") || !GetKey("z")) {
        Sleep 10
    }
    return true
}
In this snippet, the loop continues until both conditions are met. The Sleep 10 command prevents the script from consuming excessive CPU resources by yielding control to other processes for ten milliseconds during each iteration. This method is highly reliable because it directly queries the state of the operating system's input buffer for each specific key.

Combining Keys with Logical Operators

While the loop method is explicit, you can also achieve similar results by using logical operators within conditional blocks. AutoHotkey supports the logical OR (||) and AND (&&) operators, which allow you to create complex boolean expressions. When waiting for any one of several keys to be pressed, you use the OR operator. When waiting for all specified keys to be pressed, you use the AND operator.
if (GetKey("LButton") && GetKey("RButton")) {
    MsgBox Both mouse buttons are pressed!
}
This syntax is cleaner for simple checks but can become verbose if you are checking for many different combinations. It is important to note that GetKey checks the current state at the moment of evaluation. If you need to trigger an action only once when the combination occurs, you should wrap this check in a hotkey definition or a dedicated thread to avoid continuous triggering.

Handling Modifier Keys Specifically

Modifier keys like Shift, Control, Alt, and Win behave slightly differently in some contexts, but GetKey handles them uniformly. You can specify the modifier by its name, such as "Shift", "Ctrl", "Alt", or "Win". For left and right variants, you can append L or R, such as "LShift" or "RControl". This specificity is useful if your automation requires distinguishing between left and right modifiers, although for most general purposes, the generic name suffices. It is also worth noting that some applications may consume modifier keys before your script sees them. If your script fails to detect a key press, ensure that the target application is not intercepting the input. Using #UseHook at the top of your script can help by forcing AutoHotkey to install a low-level keyboard hook, which increases the priority of your script's input handling. Mastering Multiple Commands on One Line with AutoHotkey demonstrates how to streamline the actions taken after your key detection logic completes, ensuring your script remains efficient and readable.

Troubleshooting Common Issues

If your script does not respond to key presses, verify that the key names are spelled correctly and case-insensitively. AutoHotkey is generally case-insensitive for key names, but consistency helps readability. Additionally, ensure that no other script or system process is holding the key down. You can use the KeyHistory built-in feature to see what keys the system has recently registered, which helps diagnose whether the input is reaching the OS level. Another common issue is the timing of the check. If you are checking for a key combination in a tight loop without a Sleep, your CPU usage will spike. Always include a small delay in your waiting loops. Furthermore, if you are working with non-standard keys or media keys, you might need to refer to the AutoHotkey documentation for specific virtual key codes, as some special keys do not have standard text names. AutoHotkey Not Sending Commands: A Troubleshooting Guide for Tech Support provides additional context on ensuring your script's commands are executed correctly after the initial detection phase.

Frequently Asked Questions

Can I use scan codes instead of virtual keys?

Yes, you can use scan codes by prefixing the key name with SC (e.g., SC021), but they are hardware-dependent and may not work across different keyboard models. Virtual keys are recommended for portability unless you have a specific reason to target a physical key location.

How do I detect three keys pressed at once?

You can extend the logical AND operator to include three conditions, such as if (GetKey("Ctrl") && GetKey("Shift") && GetKey("z")). Ensure you add a Sleep command in any loop used to monitor these states to prevent high CPU usage.

Why is my script missing key presses?

This often happens if another application is capturing the input or if the script lacks a low-level hook. Adding #UseHook to the top of your script forces AutoHotkey to monitor input at a lower level, increasing reliability.

Does GetKey work for mouse buttons?

Yes, GetKey works for mouse buttons as well. You can use "LButton", "MButton", or "RButton" to check the state of the left, middle, or right mouse buttons respectively.

What is the difference between Wait and GetKey?

Wait is typically used for hotkeys and pauses execution until a specific key is pressed. GetKey is a function that returns a boolean value indicating the current state of a key, making it more flexible for custom logic loops and conditional checks.

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