7
votes

Using AutoHotKey, I have a rather simple loop script that I want to be able to break by the stroke of a key. I tried a few different codes from websites but it doesn't seem to work.

Here's the code:

#g::
Loop 20
{
    MouseClick, left,  142,  542
    Sleep, 1000
    MouseClick, left,  138,  567
    Sleep, 1500
    MouseClick, left,  97,  538 
    Sleep, 1000
}
4

4 Answers

2
votes

Use a global variable (keepCycling) and toggle it to break the loop. Global variables should be declared in the beginning of a script.

1
votes

Adding a global variable might be the easiest solution for your case since your loop takes a while to complete.

global break_g = 0 

#b::
    break_g = 1 
return


#g::
break_g = 0
Loop 20
{
    MouseClick, left,  142,  542
    Sleep, 1000
    MouseClick, left,  138,  567
    Sleep, 1500
    MouseClick, left,  97,  538 
    Sleep, 1000
    if( break_g = 1)
    {
        return
    }
}
return ; also you were missing this return 
0
votes
#g::  
Loop 20  
{  
    KeyWait,Ctrl,D T0  
        if Errorlevel = 0  
            break  
    MouseClick, left,  142,  542  
    KeyWait,Ctrl,D T0  
        if Errorlevel = 0  
            break  
    Sleep, 1000  
    KeyWait,Ctrl,D T0  
        if Errorlevel = 0  
            break  
    MouseClick, left,  138,  567  
    KeyWait,Ctrl,D T0  
        if Errorlevel = 0  
            break  
    Sleep, 1500  
    KeyWait,Ctrl,D T0  
        if Errorlevel = 0  
            break  
    MouseClick, left,  97,  538  
    KeyWait,Ctrl,D T0  
        if Errorlevel = 0  
            break  
    Sleep, 1000  
}  

return

Using the above can be helpful as the effect would be instantaneous. More often than not, you will have your loop stopped when you hold Ctrl for an interval.

0
votes

Toggling global variable is the way to go. You need to declare it in the beginning of the script.

global keep_working = 1 ; set break to off in the beginning of the script

b:: ; set break on keep_working = 0 return

g:: ; set working to on and start the loop keep_working = 1
Loop, ; loop until b is pressed (was loop, 20 in original code) { MouseClick, left, 142, 542 Sleep, 1000 MouseClick, left, 138, 567 Sleep, 1500 MouseClick, left, 97, 538 Sleep, 1000 if( keep_working = 0) { return ; required to stop execution } } return ; this delimiter is required at the end of hotkey procedure.