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?

6
  • What have you got so far ? Also, any specific reason why you want to differentiate between the two ?
    – Gishu
    Jun 14, 2010 at 5:40
  • 1
    Can you give additional details?
    – jfs
    Jun 14, 2010 at 5:41
  • Since no one else has asked...why would you want to differentiate between the two?
    – jrista
    Jun 14, 2010 at 5:50
  • I am making small game in C# so I want to do this. plz don't ask reason............ Jun 14, 2010 at 5:54
  • 2
    @Govind, it is generally acceptable to ask why you want to do something. For example, you said you're developing a game, have you perhaps looked at XNA (a .NET system which you can program in C#). XNA has native support for distinguishing individual key presses.
    – Ray Hayes
    Jun 14, 2010 at 6:10

3 Answers 3

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
1
  • 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). Dec 15, 2021 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).

2
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.