autohotkey

Is there a way to make each key stroke be a hard once per stroke, AHK


I dont code at all so take this as making a good action, im running a regedit macro for a game and it conflicts with my autohotkey script, as in macro i mean multiple and faster inputs for each key stroke, so it makes it easy to miss the hotkeys, as the key starts repeating itself if i press it for "too long". I want to know if there's a way to make to make each hotkey a hard once per stroke if that makes any sense, so even if i hold it it doesnt start repeating itself.

5::sendinput 2zzz capslock::sendinput 2xxxx

An example of the ahk script

As i said i dont know how to code.


Solution

  • The simplest way to do this would be by using KeyWait.

    5::
        SendInput 2
        KeyWait 5
    Return
    
    CapsLock::
        SendInput 2
        KeyWait CapsLock
    Return
    

    However, you'll quickly run into threading problems. To see this in action, using this example, press and hold 5, then press and hold CapsLock, then release 5 and try pressing it again. It'll no longer send 2 (that is, the 5 hotkey will fail to trigger because CapsLock hotkey's KeyWait has effectively overridden its own). Similarly, if #MaxThreadsPerHotkey is configured to anything but 1, each hotkey, when held, will trigger that many times before stopping.

    Therefore, a better way would be to keep track of what key has been pressed in a shared object (source). Here's how that would look:

    5::
        PreventRepeating()
        SendInput 2
    Return
    
    CapsLock::
        PreventRepeating()
        SendInput 2
    Return
    
    PreventRepeating()
    {
        Static PrevRep := Object()
        If PrevRep[A_ThisHotkey]
            Exit
        If InStr(A_ThisHotkey,"Up")
        {
            PrevRep[SubStr(A_ThisHotkey,1,-3)] := False
            Exit
        }
        PrevRep[A_ThisHotkey] := True
        Hotkey %A_ThisHotkey%%A_Space%Up,%A_ThisHotkey%
    }