clayton33
clayton33

Reputation: 4216

How can I interrupt a loop by pressing "any" key in AHK?

I currently have a script that repeatedly presses the left mouse button, until the script is interrupted. To start and stop the script the ALT+2 is pressed. How can I have it start with ALT+2 but stop by pressing any key?

#MaxThreadsPerHotkey 3
!2::  ; ALT+2 hotkey 
#MaxThreadsPerHotkey 1
if KeepWinZRunning  
{
    KeepWinZRunning := false  ; 
    return  ; 
}

; Otherwise:
KeepWinZRunning := true
Loop
{
    ToolTip, Press ALT+2 again to stop.
    Sleep 100
    Send, {VK01 down}{VK01 up}
    Sleep 100
    if not KeepWinZRunning  

        break  ; Break out of this loop.

}
KeepWinZRunning := false  ; Reset in preparation for the next press of this hotkey.
ToolTip
return

ExitApp
F12::ExitApp

Upvotes: 3

Views: 6356

Answers (2)

MCL
MCL

Reputation: 4085

As per my comment, here's an example using Timers and Input:

endKeys={enter}{tab}{LControl}{RControl}{LAlt}{LWin}{RWin}{AppsKey}{F1}{F2}{F3}{F4}{F5}{F6}{F7}{F8}{F9}{F10}{F11}{F12}{Left}{Right}{Up}{Down}{Home}{End}{PgUp}{PgDn}{Del}{Ins}{BS}{Capslock}{Numlock}{PrintScreen}{Pause}

!2::
    SetTimer, SendSomething, 200
    Input, pressedKey, I L1, % endKeys
    SetTimer, SendSomething, Off
return

SendSomething:
    Send, {VK01 down}{VK01 up}
return

You may have to complete the list of endkeys, depending on your keyboard layout.

Upvotes: 4

bgmCoder
bgmCoder

Reputation: 6370

Take a look at this post. Here is a direct quote. You should look at the original post for details (I can't take credit for it), but here is the snippet:

#InstallKeybdHook  ; this MUST be called at the start of your script

AnyKeyPressed() ; returns a 1 if any keyboard key is pressed, else returns 0
{
    if( A_TimeIdlePhysical < 25 )
        return 1

return 0
}

Upvotes: 1

Related Questions