Autohotkey - GetKeyState breaks if a new key is pressed
Matthew Harrington
I'm trying to create a script that presses the space button, as long as it is physically pressed.
By example, if I hold down the space bar, the script would replicate spaces with Send. As soon as I release the spacebar, it stops sending space.
I've achieved this with this script
#NoEnv
#SingleInstance Force
SendMode Input
loop { if (GetKeyState("Space")) { Send {Space down} Random, r, 5, 15 Sleep, %r% Send {Space up} } Random, r, 5, 10 Sleep, %r%
}
Esc::
ExitApp
returnThis works, however, if I press a new key while pressing the Space button, the GetKeyState("Space") would return false for some reason.
The script currently starts properly, but pressing any other key is the same as releasing the spacebar, which is not what I want.
So then I thought, maybe Input can help me. Well, again, it worked, but as soon as I pressed a different key, it would stop.
Here's what I tried with Input that produced the same results, relatively (with offsets in timing) from the first sample I tried.
#NoEnv
#SingleInstance Force
SendMode Input
loop { Input, OutputVar, B I L4 T0.05 V ; Had to keep it a low timeout due to the nature of the script if (InStr(OutputVar, Chr(32))) { Send {Space down} Random, r, 5, 15 Sleep, %r% Send {Space up} } Random, r, 5, 10 Sleep, %r%
}
Esc::
ExitApp
returnThis also fails because pressing a new key internally releases my spacebar from being pressed.
I'd try to do keybind events like Space::, but it would also be fired from the Send commands, creating an infinite loop. And I wouldn't want to press any other key than space, as several of my keys are binded to something or another.
It feels like filter keys, or sticky keys, because even without autohotkey, the spacebar releases after pressing any other key. But both of those features are turned off. And it's not just the spacebar. Any held key is released as soon as a new key is pressed. Filter keys does exactly what I'm trying to prevent, but there's no 'reverse filter keys' so to speak. Is it possible to get by with this hardware limitation? How can I have autohotkey work in the sense where it see's that I'm holding space, even after a new key has been pressed?
2 Answers
This is old but it could help people in the future with the same problem.
Instead of GetKeyState("Space") use GetKeyState("Space", "P") to check the physical state of the key
When another key is pressed after the spacebar, GetKeyState doesn't capture the spacebar anymore. It's like when you're spamming "A" by long pressing it, and then proceed to long press "B" without releasing "A", you don't get "aaaababab" but just "aaabbbbb". I don't get what you're trying to do when you press a different key as you press spacebar (It could be that you want a combination of spamming?), but I believe what you're trying to achieve isn't possible.
1