Bali C
Bali C

Reputation: 31251

C# P/Invoke keyboard_event

I have been using some P/Invoke code to simulate a key press, but I can't work out how to press more than one key at once. I am trying to simulate pressing and holding CTRL and then pressing C and then V, so just a copy and paste.

The code I am using so far is this, but so far I can only manage to press CTRL, not hold it and press C and V:

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

public const int VK_LCONTROL = 0xA2;

static void Main(string[] args)
{
   keybd_event(VK_LCONTROL, 0, 0, 0);
}

I would really appreciate any suggestions. Thanks.

Upvotes: 4

Views: 3000

Answers (2)

ken2k
ken2k

Reputation: 49013

The dwFlags controls if the key is released or not.

Try the following:

keybd_event(VK_CONTROL, 0, 0, 0);// presses ctrl
keybd_event(0x43, 0, 0, 0); // presses c
keybd_event(0x43, 0, 2, 0); //releases c
keybd_event(VK_CONTROL, 0, 2, 0); //releases ctrl

Upvotes: 8

Chiara Coetzee
Chiara Coetzee

Reputation: 4459

keybd_event should be called twice for each keystroke, once to press it down, and once to release it, with the third argument including the bit KEYEVENTF_KEYUP. You should of course press both keys down before releasing either. See here for a working example of pressing "SHIFT+TAB" using keybd_event on the .NET Compact Framework (may be slight differences).

Note that keybd_event has been superseded by SendInput, but should still work.

Upvotes: 4

Related Questions