I want to determine whether a CTRL key is LEFT CTRL or RIGHT CTRL key when it is pressed. How can I do this?
-
What have you got so far ? Also, any specific reason why you want to differentiate between the two ?– GishuCommented Jun 14, 2010 at 5:40
-
1Can you give additional details?– jfsCommented Jun 14, 2010 at 5:41
-
Since no one else has asked...why would you want to differentiate between the two?– jristaCommented Jun 14, 2010 at 5:50
-
I am making small game in C# so I want to do this. plz don't ask reason............– Govind MalviyaCommented 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 HayesCommented Jun 14, 2010 at 6:10
3 Answers
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
-
1To 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). Commented Dec 15, 2021 at 14:03
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).
-
This is no longer the correct answer - see stackoverflow.com/a/49847252/4658148 Commented Dec 15, 2021 at 13:56
-
1Thanks @JacekKołodziejek - answer edited to make this clearer. Commented Dec 16, 2021 at 23:00
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.