I'm trying to simulate keyboard commands for a custom game controller application. Because I'll need to simulate commands in a DirectInput environment most of the usual methods don't work. I know that using a hook would work 100% but I'm trying to find an easier implementation.

I've done quite a bit of searching and found that by using the SendInput API with Scancodes instead of virtual keys should work, but it seems to behave like the key's are "sticking". I've sent both the KEYDOWN and KEYUP events but when I attempt to send the message in a DirectInput environment, the game acts as if the key is being held down.

For instance, if I simulate a "W" keypress and have that key mapped in a First Person Shooter to the "move forward" action, once I'm in game, the function below will cause the character to move forward. However, just by issuing the command once, it will move the character forward indefinitely.

Here is a code snippet (in C#) for the SendInput function I'm calling:

I'm not sure if this method is a lost cause, or if there is just something silly I'm missing. I hate to over complicate my code if I don't have to by using hooks, but this is also new territory for me.

2 Answers
2

I've found the solution to my own problem. So, I thought I'd post here to help anyone who may have similar issues in the future.

The keyup command was not working properly because when only sending the scan code, the keyup must be OR'ed with the scan code flag (effectively enabling both flags) to tell the SendInput() API that this is a both a KEYUP and a SCANCODE command.

For instance, the following code will properly issue a scan code key-up:

Thanks to Hans for the response. I did some investigating and sending two messages back to back like the original example does indeed simulate a "keypress" but it's very fast. It would not work well for a movement command, but would be ideal when action keys are to be "tapped" and not held down.

Also, the virtual key field is ignored when sending a scan code. MSDN had the following to say on the subject:

"Set the KEYEVENTF_SCANCODE flag to define keyboard input in terms of the scan code. This is useful to simulate a physical keystroke regardless of which keyboard is currently being used. The virtual key value of a key may alter depending on the current keyboard layout or what other keys were pressed, but the scan code will always be the same."

In your solution found you mention a DirectInputKeyScanCode, that i can´t get it in use, could you help me?
–
FedeSep 10 '13 at 1:43

Could you post a full solution for pressing a key down and key up? I am not sure what i am doing wrong and what i need to replace in the first code snippet you have sent. THX!
–
Stefan VasiljevicApr 15 '14 at 3:43

I was trying to simulate keyboards for a presentation in Flash, and was also having the same problem. It did work for apps like Notepad, but not for flash. After hours of googling I finally made it work: