AHK - 在函数内休眠不起作用

AHK - Sleep inside a function doesn't work

以下代码按预期工作:

time := 1000

<^q::
    Sleep time
    SendInput {F9}
return

但是,下面的代码没有(它完全忽略了 Sleep),我不确定为什么:

time := 1000

<^q:: 
    doKeys()
return

doKeys()
{
    Sleep time
    SendInput {F9}
}

您的第一个示例之所以有效,是因为 Subroutine (gosub) 中包含的代码可以访问可变时间。

Functions

A function is similar to a subroutine (Gosub) except that it can accept parameters (inputs) from its caller. In addition, a function may optionally return a value to its caller.

time := 1000

<^q:: 
    doKeys(time) ; Pass your variable to the function
return

doKeys(x) ; Set your function to accept a variable
{
    Sleep x
    SendInput {F9}
}

或者,您可以将变量声明为 Global,这样无需将其传递给函数即可访问它。

time := 1000

<^q:: 
    doKeys() 
return

doKeys() 
{
    global time
    Sleep time
    SendInput {F9}
}

使变量成为全局变量:

time := 1000

<^q:: 
    doKeys()
return

doKeys()
{
    global time
    Sleep time
    SendInput {F9}
}

注: 如果你使用#Warn,如果代码中有常见错误,AHK会给你一个警告。