You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AHK实现Ctrl键长短按检测问题:需忽略Ctrl+其他按键组合

修改后的AutoHotkey脚本

要解决Ctrl组合键被误判为长按的问题,我们需要在检测Ctrl按键模式的同时,监控是否有其他按键被按下。如果检测到其他按键,则跳过模式判断,保留系统默认的组合键行为。以下是修改后的完整脚本:

Morse(timeout = 150, ByRef abort) {
    tout := timeout/1000
    key := RegExReplace(A_ThisHotKey,"[\*\~\$\#\+\!\^")
    Loop {
        if (abort)
            return ""
        
        ; 等待按键按下,同时检查是否需要终止
        while !GetKeyState(key, "P") && !abort {
            Sleep 10
        }
        if (abort)
            return ""
        
        t := A_TickCount
        ; 等待按键释放,同时检查是否需要终止
        while GetKeyState(key, "P") && !abort {
            Sleep 10
        }
        if (abort)
            return ""
        
        Pattern .= A_TickCount-t > timeout
        
        ; 等待下一次按键或超时,同时检查是否需要终止
        start := A_TickCount
        while (A_TickCount - start) < timeout && !GetKeyState(key, "P") && !abort {
            Sleep 10
        }
        if (abort)
            return ""
        
        if (!GetKeyState(key, "P"))
            Return Pattern
    }
}

~Ctrl::
    abort := false
    SetTimer, CheckForOtherKeys, 20
    p := Morse(150, abort)
    SetTimer, CheckForOtherKeys, Off
    
    ; 如果检测到其他按键,直接返回,不触发消息框
    if (abort || p = "")
        return
    
    If (p = "0")
        MsgBox Short press
    Else If (p = "1")
        MsgBox Long press
    Else If (p = "00")
        MsgBox Two short presses
    Else If (p = "01")
        MsgBox Short+Long presses
    Else
        MsgBox Press pattern %p%
    Return

CheckForOtherKeys:
    ; 遍历所有按键,检查是否有非Ctrl键被按下
    Loop, 255
    {
        ; 跳过左右Ctrl键
        if (A_Index = 162 || A_Index = 163)
            continue
        ; 检测当前按键是否处于按下状态
        if (DllCall("GetAsyncKeyState", "int", A_Index) & 0x8000)
        {
            abort := true
            SetTimer, CheckForOtherKeys, Off
            return
        }
    }
    return

关键修改说明

  1. 新增终止标志(abort):通过引用传递的方式让Morse函数可以检测到是否需要终止模式判断
  2. 按键监控定时器:在Ctrl按下后启动定时器,持续检查是否有其他按键被按下
  3. 修改Morse函数:在等待按键的各个阶段加入终止检查,一旦检测到其他按键立即退出
  4. 组合键处理:如果检测到其他按键,直接跳过后续的模式判断和消息框,保留系统默认的组合键功能

内容的提问来源于stack exchange,提问作者Afshin Davoudy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 13:05:14