Search code examples
loopsreturnautohotkeybreaknested-function

End execution without script closure by keypress?


Question

  • Basically, the title says it all! How do I stop execution of my hotkey via a hotkey?
  • How do I do so without closing the script?
  • How do I explicitly set a hotkey to take priority over a specific loop?

Explanation

I have a loop that executes several hundred times (code attached), and I would like to create a kill switch. I don't want to have to re-open the script if I stop it running, and I need to have lengthy sleeps, so I can fool with the mouse, as it is.

I'm looking at various pages, such as tutorial and break.

What I've tried

For example, should I name my loop somehow? Because Break takes no parameters, I'm thinking: there's no way to specify what to break.

Another example: should I add a hotkey into my loop to break? If so, how do I do that? Just throw ^!p:: into a nest under each hotkey? Or is there another way to add a hotkey to a hotkey (for example, with GetKeyState)?

Answer format

If possible, please show don't tell your answers, using the following code:

^!i::
{
    Loop 1300
    {
        Send ^+{PrintScreen}
        Sleep 1500
        MouseClickDrag, left, 0, 100, 600, 400
        Sleep 1000
        Send 1
        Sleep 500
    }
    Return
}
^!o::
{
    Loop 1323
    {
        Send ^+{PrintScreen}
        Sleep 1500
        MouseClickDrag, left, 0, 200, 600, 400
        Sleep 1000
        Send 1
    }
    Return
}

Solution

  • If you want a controlled stop, i.e. at a certain point in the script, then you could use a hotkey to set a variable and test that variable in the script. When the variable has been set and the IF statement is true, you reset that variable and exit the loop. Otherwise, you could kill the script at a random point through the reload command. This way the script is closed, but immediately reopened.

    ^!i::
    MyStopVariable:=0 ; Set the variable to 0
    Loop 1300
    {
        If MyStopVariable
            Exit ; Or Break if you want to finish something of after the loop
        Send ^+{PrintScreen}
        Sleep 1500
        MouseClickDrag, left, 0, 200, 600, 400
        Sleep 1000
        If MyStopVariable
            Exit ; Or Break if you want to finish something of after the loop
        Sleep 500
    }
    Return
    
    ^!o::
    MyStopVariable:=0 ; Set the variable to 0
    Loop 1323
    {
        If MyStopVariable
            Exit ; Or Break if you want to finish something of after the loop
        Send ^+{PrintScreen}
        Sleep 1500
        MouseClickDrag, left, 0, 200, 600, 400
        Sleep 1000
        If MyStopVariable
            Exit ; Or Break if you want to finish something of after the loop
        Send 1
    }
    Return
    
    ^!s:: ; Ctrl+Alt+s = stop
    MyStopVariable:=1
    Return
    

    Alternatively, you could use your original code and add a reload.

    ^!s:: ; Ctrl+Alt+s = stop
        Reload
    Return