简体   繁体   中英

How to interrupt a loop with a hotkey

This should be easy! I've checked out this thread , but it doesn't help.

I can't seem to break out of the loop using the hotkey. The idea is that you can start and stop the looping process with a single hotkey.

It seems like the value of timeron never gets into the the loop once it's begun.

Here is a sample script:

#singleinstance force

timeron = 0
return

!f7::
    if(timeron){
        timeron = 0
        msgbox Okay, the loop is off.
    }else{
        timeron = 1 ;if this is not set to one, the loop will not begin
        msgbox Turning on the loop.
        gosub, STARTLOOPING
    }
RETURN


STARTLOOPING:
    ;do this over and over
    loop{
        if(!timeron)
            break   
        ;now wait for the right length of time before continuing the loop
        msgbox, The loop yet continues....
        Sleep, 5000
        if(!timeron)
            break
    }
RETURN

What am I missing here?

Since your !F7 never ends, a second press of !F7 is ignored. Per default there is only one thread for each hotkey allowed at one time.

Add

#MaxThreadsPerHotkey 2

as a second line to your script then the second !F7 press can deactivate the loop.

Why don't you use timers instead? They allow your script to do other stuff in between timer runs, thus allowing hotkeys to interrupt them:

timeron := false
Exit
!F7::
    if(timeron) {
        timeron := false
        SetTimer, MyTimer, Off
    } else {
        timeron := true
        ; Call GoSub once if you want the subroutine
        ; to fire immediately at the beginning
        GoSub, MyTimer
        ; Then let the timer repeat it
        SetTimer, MyTimer, 5000
    }
return

MyTimer:
    Msgbox, Looping like crazy!
return

You can always replace a loop's functionality with a timer. If you have some kind of for loop/counter, you can use global variables instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM