Vitalliuss
Vitalliuss

Reputation: 1732

How to make virtual key up after sending key combination in c# using WinAPI

I've got the strange issue with sending key combination using winapi in c#. My goal is to create a method for sending two keys, f.e. SHIFT + HOME:

 private const int WM_KEYDOWN = 0x0100;
 private const int WM_KEYUP = 0x0101;

 [DllImport("user32.dll")]
 static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);

 public static void SendKey(byte key1, byte key2)
 {
      //SHIFT down
      keybd_event(key1, 0, WM_KEYDOWN, UIntPtr.Zero);
      //press HOME
      keybd_event(key2, 0, WM_KEYDOWN, UIntPtr.Zero);
      keybd_event(key2, 0, WM_KEYUP, UIntPtr.Zero);
      //SHIFT up
      keybd_event(key1, 0, WM_KEYUP, UIntPtr.Zero);
 }

The issue is that key1 (SHIFT) is still pressed after the method finishes execution. In other words the additional method call will start with pressed SHIFT from the previous run. It looks extremely simple but I can't find the solution to make it working. I've looked at lots of related SO questions and tried them but the issue is still actual. Any help is appreciated.

Upvotes: 0

Views: 1599

Answers (1)

Aleksander Bavdaz
Aleksander Bavdaz

Reputation: 1346

Check the keybd_event documentation! In particular the flags for the 3rd parameter. In your code you've been pressing each key twice and not releasing either.

Replace your window message constants with KEYEVENTF_KEYUP (0x2) to depress and simply zero for keydown.

Also you may want to look at .NETs SendKeys class.

Upvotes: 1

Related Questions