How to get ExitApp to take effect immediately in AHK?

Viewed 904

If I run the following code, if I hit the ^+q it does not stop entering the numbers 1-100. Only after it completes does the script exit. Is there a way to get the script to stop even if it is in the middle of sending keystrokes?

^j::
ArrayCount := 100

Loop % ArrayCount
{
Send, %A_index%
}
return

^+q::ExitApp  ; Exit script with Escape key
1 Answers

There are 2 issues with your code.

Sendreleases modifier keys when it simulates input, using it in a loop this way is going to interfere with autohotkey's hotkey detection. You can still activate ^+q if you press the 3 buttons simultaneously but it's much easier to use a hotkey without modifiers for example the Escape key. This is also what your comment says you're doing

^+q::ExitApp ; Exit script with Escape key

so as a bonus it will fix the discrepancy between your comment and your code ;).

The second problem is that the loop in which you execute the Send command is going to finish very quickly if you use SendInput and by the time ExitApp is executed all the numbers were already sent(even if you don't yet see the effect). In case of SendEvent there is some other problem which prevents other threads from being executed when you do it in a loop(don't know what causes it, might be a bug).

To solve it you need to add Sleep. At my system doing Sleep 1 works well. You can experiment with different numbers and send modes until you get the desired effect(you can also try 0 and -1.

Full code:

^j::
ArrayCount := 100
Loop % ArrayCount
{
    Send %A_index%
    Sleep 1 ; experiment with how long to sleep
}
return

Escape::ExitApp  ; Exit script with Escape key
Related