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

IE浏览器keydown事件中无法区分Ctrl与AltGr键如何解决

解决方案

方案1:使用event.location属性直接区分(更简单,推荐)

IE 1909版本支持window.event.location属性,该属性返回按键的物理位置标识,二者的返回值存在明确差异:

  • 单独按下任意Ctrl键时,keyCode=17对应的location值为1(左Ctrl)或2(右Ctrl)
  • 按下AltGr触发的keyCode=17事件,对应的location值固定为3(扩展按键位置)
    修改后的检测代码如下:
sub document_onkeydown()
    dim keyCode, ctrlKey, location
    keyCode = window.event.keyCode
    ctrlKey = window.event.ctrlKey
    location = window.event.location
    
    if keyCode = 17 and ctrlKey = true then
        if location = 3 then
            MsgBox "按下的是AltGr键"
        else
            MsgBox "按下的是Ctrl键,位置:" & iif(location=1,"左侧","右侧")
        end if
    end if
end sub

方案2:通过事件序列特征区分

如果遇到特殊键盘布局下location属性返回异常的情况,可以利用AltGr的事件触发特性判断:
按下AltGr时,IE会在极短间隔(通常<15ms)内连续触发两次keydown事件,先触发keyCode=17(Ctrl),紧接着触发keyCode=18(Alt);而单独按Ctrl只会触发一次keyCode=17事件,不会后续紧跟Alt的keydown事件。
实现代码如下:

dim lastCtrlTime, lastCtrlLocation
' 存储上次Ctrl按键的时间和位置
sub document_onkeydown()
    dim keyCode, currTime
    keyCode = window.event.keyCode
    currTime = timer() * 1000 ' 转换为毫秒级时间戳
    
    if keyCode = 17 then
        lastCtrlTime = currTime
        lastCtrlLocation = window.event.location
    elseif keyCode = 18 then
        ' 检测到Alt按键和上次Ctrl按键间隔小于20ms,判定为AltGr按下
        if currTime - lastCtrlTime < 20 then
            MsgBox "按下的是AltGr键"
            ' 标记为已处理,避免后续误判单独Alt按键
            lastCtrlTime = 0
        end if
    end if
end sub

内容的提问来源于stack exchange,提问作者andré marquis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 18:45:02