Reputation: 9
I'm reading a key through the KeyDown event, however I'd like to try to interpret it by seeing what that key would be had num lock be pressed (and on). Is there a way to do that?
I don't want to programatically set the state of numlock because then I'm sort of at the mercy of the user and have to manage that state. Also, I have to support any keyboard.
Upvotes: 0
Views: 783
Reputation: 480
I made a little test project and overrode the ProcessCmdKey to catch any keyboard input. I have a standard keyboard with extra NumPad. When I press a number Key with the NumPad enabled I get NumPadX as keyData
and when I disable NumLock and press one of the keys again I just get for example Left
when pressing the 4 key. All possible values can be found in the Keys enum
Overriding the ProcessCmdKeymethod
will basically give you the very first chance to catch any key input in your application. What you won't be able to do is to guess how the keyboard hardware is designed and sends the key press to the OS.
Upvotes: 0
Reputation: 63772
There's multiple levels to interpreting keyboard input.
On one level, you get characters - so if the user presses F
, you'll get a character f
. If the user presses Shift+F
, you'll get F
. Similarly, if the user presses Num 8
with the numlock on, you'll get 8
(the same as if he pressed alpha-numeric 8
) - but if he presses Num 8
without the numlock on, you'll get nothing.
On another level, you get keys. If the user presses F
, you'll get Keys.F
. If he presses Shift+F
, you get Shift+F
. On the numeric pad, pressing Num 8
with numlock on gives you Num 8
(different from alpha-numeric 8
) - but pressing it with numlock off gives you Up
.
In .NET, those two view of the keyboard are exposed by the KeyPress
event for characters, and the KeyDown
/KeyUp
events for keys.
However, note that neither of the two allows you to reinterpret the numeric keypad the way you want! For example, on my keyboard, both pressing the Up
key and pressing Num 8
with numlock offs gives you the same key - that's because they are logically the same.
More importantly, different keyboards work differently. For example, many laptop keyboards have their numpad on the alpha-numeric keyboard. So if your numlock is off, the same key that used to be Num 8
is now I
or something like that. Adapting for weird keyboard layouts is basically the same as writing drivers for each and every keyboard out there - you really don't want to do that.
Upvotes: 3