2

I want to determine whether a CTRL key is LEFT CTRL or RIGHT CTRL key when it is pressed. How can I do this?

Mwiza
  • 7,780
  • 3
  • 46
  • 42
Govind Malviya
  • 13,627
  • 17
  • 68
  • 94

3 Answers3

3

You can easily check the status of the Keyboard using System.Windows.Input.Keybaord.IsKeyDown() to determine if the Right or Left Control key is pressed:

if (Keyboard.IsKeyDown(Key.LeftCtrl)
     {}
else if (Keyboard.IsKeyDown(Key.RightCtrl)
     {}
end if
Peter
  • 364
  • 5
  • 17
  • To clarify, the System.Windows.Input.Keyboard.IsKeyDown() method requires PresentationCore.dll (Add Reference -> Assembies -> Framework -> PresentationCore). The System.Windows.Input.Key enum is defined in WindowsBase.dll (Add Reference -> Assembies -> Framework -> WindowsBase). – Jacek Kołodziejek Dec 15 '21 at 14:03
2

Edit: You can now use System.Windows.Input.Keybaord.IsKeyDown()

  • see the other answers above. Historically you couldn't access this information from within .net - so it was necessary to do the following:

However, you can use the Win32 API GetAsyncKeyState to test if specific keys are currently down, and this can differentiate the left and right ctrl keys. (If you're writing a game this is more likely to work well for you than Keydown handlers, as GetAsyncKeyState tests whether the key is down "now" rather than whether it was pressed "at some time in the past", which gives considerably better responsiveness).

Jason Williams
  • 56,972
  • 11
  • 108
  • 137
0

Apparently not from within .NET, but it's possible from the Win32 APIs.

  • The System.Windows.Forms.Key enumeration tracks left, right, and middle mouse buttons, but only has one flag for Control keys, so no way to determine left or right for Control keys.
  • The Console.ReadKey() method suffers from the same problem.
  • You might be able to do something at the Win32 level. The WM_KEYDOWN message will track the extended keys (right Alt, right Control), so Windows is tracking this data ... it just isn't being passed on to .NET. You're on your own with regard to tapping into the Win32 API from within .NET.
Craig Trader
  • 15,507
  • 6
  • 37
  • 55