Using GetKeyState() and loops

假如想象 提交于 2020-01-15 07:39:07

问题


I'm trying to write a script that has a loop in which the upper arrow key is pressed every two seconds. The loop must be activated when I press the spacebar and deactivated when I press it again. I'm now using this.

$Space::
if GetKeyState("Space", "P")
{
    Loop
    {
        Sleep 2000
        Send {Up}

        if GetKeyState("Space", "P")
        {
            return
        }
    }
}

For some reason, the if condition inside the loop doesn't work, i.e. I can't get out of the loop. I hope anyone can help me out...


回答1:


You wouldn't need the first if GetKeyState("Space", "P")
and you would need to be holding space when the loop got to the second one
for it to break; and you would need to replace the return with break.

However I agree with Gary, although I would write it like this:

; (on:=!on) reverses the value of variable 'on'
; the first press of space reverses on's value (nothing) to something (1)
; the second press reverses on's value from (1) to (0)
; when (on = 1) delay will be set to 2000, and Off when (on = 0)

space::SetTimer, Action, % (on:=!on) ? ("2000") : ("Off")

Action:
Send, {up}
Return

% starts an expression.

From http://l.autohotkey.net/docs/Variables.htm

?:
Ternary operator
This operator is a shorthand replacement for the if-else statement.
It evaluates the condition on its left side to determine
which of its two branches will become the final result.
For example, var := x>y ? 2 : 3 stores 2 in Var if x is greater than y; otherwise it stores 3.




回答2:


How about using SetTimer?

; Create timer.
SetTimer, SendUp, 2000 

; Set timer to 'Off' at start of script.
SetTimer, SendUp, Off
TimerEnabled := False

; When Space is pressed toggle the state of the timer.
$Space::
    If TimerEnabled
        {
        SetTimer, SendUp, Off
        TimerEnabled := False
        }
    Else
        {
        SetTimer, SendUp, On
        TimerEnabled := True
        }

; Label called by timer to send {Up} key.
SendUp:
    Send, {Up}
return


来源:https://stackoverflow.com/questions/9623516/using-getkeystate-and-loops

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!