我在 AHK 中遇到 GetKeyState 问题

I'm having trouble with GetKeyState in AHK

下面是我编写的一个 alt+tab 程序,由于某种原因,它无法运行。

while x = 1
{
    mb1 := GetKeyState(j)
    mb2 := GetKeyState(k)
    if (mb1 = 1) and (mb2 = 1)
    {
        Send, {Alt Down}
        Send, {Tab Down}
        sleep, 50
        Send, {Alt Up}
        Send, {Tab Up}
    }
}

我尝试了多种循环和按键检测的方法都无济于事。

您不需要在 if 语句之前将 keystate 的值存储在变量中;您可以在 if 语句中检查它们。

因此,您可以通过如下方式实施此更改:

Loop
{
    if (GetKeyState("j") && GetKeyState("k"))
    {
        Send, {Alt Down}
        Send, {Tab Down}
        sleep, 50
        Send, {Alt Up}
        Send, {Tab Up}
    }
}

但是,如果您出于某种原因需要保存 KeyStates 的值,有两种方法可以做到这一点:

  1. Just save the values from the GetKeyStates while you are checking them in the if-statement.

注意:为了使两个变量始终在每次迭代中更新,您需要将高效的 && 替换为效率较低的 &,因为 && 将尽快停止检查变量因为它确定表达式将为假。

这看起来像:

Loop
{
    if (mb1:=GetKeyState("j") & mb2:=GetKeyState("k"))
    {
        Send, {Alt Down}
        Send, {Tab Down}
        sleep, 50
        Send, {Alt Up}
        Send, {Tab Up}
    }
    
    MsgBox During the last check, j was %mb1%, and k was %mb2%!
}
  1. Use the alternative GetKeyState command syntax

注意:虽然此版本的命令可以更直接地将命令的输出保存到变量,但它已被弃用,不建议在新脚本中使用。