Search code examples
c#keyboard

How can I hold down a Key using the keybd_event in C#


I'm currently trying to develop an App that enables the user to send Keystrokes to a specific program. I already can send keys and hold down specific keys like that:

[DllImport("user32.dll", SetLastError = true)]        
static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

keybd_event(key, 0, 0, 0); //Start holding the key down
keybd_event(key, 0, KEY_UP_EVENT, 0); //Stop holding the key down

Holding Shift down while sending letters capitalizes them already. But if I'm holding down a letter (and send it to notepad for example), then just writes that letter once. If I do the same with my physical keyboard, it starts writing the letter until I let go again. Does anyone have a tip or clue how I can manage that?

I already experimented with the stopwatch, but that wasn't working either.


Solution

  • Thanks to @RaymondChen , this question has been answered.

    Physical keyboards have a feature called "typematic" which autorepeats characters which are held down. You'll have to emulate that too.

    If you want to simulate the repetition of a keystroke, just send multiple KeyDown and KeyUP-Events.