Fundamental flaw in your recommended AutoFire method

Not sure if you are aware, but this is a horrible way to do AutoFire:

~$a::
    ; This checks to see if the "a" key is still being "P"ushed down
    While GetKeyState("a", "P"){
        ; While the "a" key is held down, send a
        Send, a
        ; Puts a pause in so it doesn't send too many As
        Sleep, 50
    }
return

It ties up the main thread, which may well cause problems if you have other code in your script.
Furthermore, if someone wishes to change the hotkey, they have to change it in two places - why not While GetKeyState(A_ThisHotkey)?

Anyway, this technique is all fine and dandy when your scripts are real simple, but as you get better you may well start running into issues caused by doing this.

eg here is what happens if you tried to duplicate the code twice (ie one hotkey for A, one for B):

Hold A, spamming starts. Hold B, A stops spamming and B starts. Keep holding A but release B - all spamming stops.
Note that if B is a keyboard key, then B will restart after a while, but ONLY because key repeat re-fired the hotkey, not because B resumed after it was interrupted by A. If B is a mouse button (That does not repeat) then B will not restart. Imagine how baffled someone would be if this happened to them - it takes a fairly deep understanding of AHK to appreciate the issues at play.

Also, it is CPU inefficient, as you are doing a key check VERY quickly, when you have up events provided for you...

The only way to have two things "running at the same time" is to use SetTimer and each tick of the timer MUST be allowed to finish (ie don't just do a SetTimer, MyLabel, -0 and jump to an infinite loop).

Seeing as the SetTimer command is so simple to use, why not just recommend that from the get-go?

XButton1::
    SetTimer, Do1, 100
    return

XButton1 up::
    SetTimer, Do1, Off
    return

Do1:
    ToolTip % "1: " A_TickCount, ,10
    return

XButton2::
    SetTimer, Do2, 100
    return

XButton2 up::
    SetTimer, Do2, Off
    return

Do2:
    ToolTip % "2: " A_TickCount, ,40
    return

Posted Jun 16, 2017, 7:43 PM UTC · edited

94
Loading comments…