如何在AHK中为按键轻按与长按1000ms配置不同的热键行为
AutoHotkey: Short Press → Esc, Long Hold → Run Target Script
Got it, let's build this behavior step by step. The core trick is using KeyWait with a timeout to tell short presses apart from long holds, then triggering the right action for each case. Here's a complete, tested script that does exactly what you need:
; Replace F1 with your target key (e.g., CapsLock, Space, X, etc.) $F1:: ; Wait up to 1000ms (1 second) for the key to be released KeyWait, F1, T1 if (ErrorLevel) { ; Key was held longer than 1 second ToolTip, Executing long-hold action... ; Optional visual feedback ; Replace the line below with your desired script/action Run, "C:\Path\To\Your\CustomScript.ahk" ; Wait for the key to be fully released to avoid unintended repeats KeyWait, F1 ToolTip ; Clear the tooltip } else { ; Key was released before 1 second (short press) Send {Esc} } return
How this works (line by line):
$F1::: The$prefix prevents the script from triggering itself when we send{Esc}—critical to avoid infinite loops. SwapF1with whatever key you want to modify.KeyWait, F1, T1: This command pauses the script and waits forF1to be released. TheT1parameter sets a 1000ms timeout.if (ErrorLevel): IfKeyWaittimes out (meaning the key is still held after 1 second),ErrorLevelgets set to 1. We then run your specified script and wait for the key to be fully released.else: If the key is released before the timeout, we send theEsckey instead.
Quick Customization Tips:
- Adjust the hold threshold: Change
T1to tweak how long you need to hold the key. For example,T0.7for 700ms,T1.5for 1500ms. - Swap the target key: Use any valid AHK key name (e.g.,
CapsLock,Space,LControl—check the official key list for options). - Replace the long-hold action: Instead of
Run, you can call a function, send a key sequence, or run any AHK command. For example:; Example: Send a custom shortcut instead of running a script Send {Ctrl}+{Shift}+{R}
This implementation is lightweight, reliable, and avoids common pitfalls like double-triggering or unexpected behavior. Test it out and tweak to fit your needs!
内容的提问来源于stack exchange,提问作者Leon Fasser
相关产品推荐
相关产品推荐

