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

Window.event.keyCode与.dat文件读取值不匹配的VBS HTA问题

问题解决:VBScript中键码数值与字符串不匹配的问题

核心原因

你遇到的是类型不匹配问题:从Bindings.dat读取的键码是字符串类型(如"27"),而Window.event.keyCode返回的是数值类型(如27)。虽然两者显示的内容相同,但VBScript在比较不同类型的值时,会触发特殊的类型转换逻辑,导致看似相等的内容无法匹配。

你的测试现象也能佐证这一点:27 = Key_close返回True是因为VBScript会自动将字符串转成数值进行比较;但后续Window.event.keyCode = Key_close返回False,大概率是因为读取的字符串包含隐藏的空白字符(如行尾的换行、空格),此时VBScript会将数值转成字符串进行比较,"27"与"27\n"或"27 "自然不相等。

解决方案

1. 强制类型转换

将从文件读取的字符串键码转换为数值类型,确保和Window.event.keyCode的类型一致:

方式一:在Read函数中直接转换

修改函数的返回语句:

' 替换原有的 Read = output
If IsNumeric(output) Then
    Read = CInt(output) ' 转换为整数类型
Else
    Read = Empty ' 处理无效键码的情况
End If

方式二:在赋值时转换

Key_close = CInt(Read("C:\Users\[login name]\Desktop\Repos\[my repo]\dat\Bindings.dat", "close"))

2. 优化Read函数,处理隐藏空白字符

在读取文件时,去除行首尾的空白字符,避免不可见字符干扰:

Function Read(Path, Var)
    Dim FSO, File, allData, ln, VarName, output
    output = Empty ' 初始化默认值
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set File = FSO.OpenTextFile(Path, 1)
    allData = File.readall
    File.Close
    For Each ln In Split(allData, vbCrLf)
        ln = Trim(ln) ' 去除行首尾的空白(空格、回车、换行等)
        If ln <> "" Then ' 跳过空行
            VarName = Split(ln, " ", 2)(0)
            If VarName = Var Then
                output = Split(ln, " ", 2)(1)
                output = Trim(output) ' 去除键码的首尾空白
                Exit For
            End If
        End If
    Next
    Set File = Nothing
    Set FSO = Nothing
    ' 转换为数值类型
    If IsNumeric(output) Then
        Read = CInt(output)
    Else
        Read = Empty
    End If
End Function

验证修改

修改后,Key_close会变为数值类型,和Window.event.keyCode的数值类型完全匹配,此时Window.event.keyCode = Key_close就能正常触发预期逻辑。

内容的提问来源于stack exchange,提问作者Arnaud Girard

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 08:05:05