0

I've been having some trouble getting the correct code for incoming keystrokes on the console for shift+number characters. For example, using:

cki = Console.ReadKey(True)
Console.WriteLine("You pressed the '{0}' key.", cki.Key)

If I press shift+2, I'm hoping to get the ascii 64 (for the '@' character), but instead I get 50 (for the '2' character).

Now, I know you can get the modifiers for the key pressed, but that would mean I'd have to program all the special cases for keys like that, and that doesn't seem right.

I need this function, or something like unto it, because of its ability to read keys as they are pressed, without the need to press enter, otherwise I'd just use console.read. Surely I've missed something. Could anyone tell me what it is I've missed?

2 Answers2

1

You're looking for the KeyChar property, which returns the actual character rather than the physical key pressed.
You may want to cast it to int.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • It looks like a bit more exploration would have solved it, then! Never code when you're tired, is the take-away lesson here =) Thanks so much for pointing me in the right direction! – user2088591 Nov 12 '13 at 21:07
1

It is pretty important to distinguish between keys and characters. The key is the same anywhere in the world, the one on the top row at the left. You can rely on that key always producing ConsoleKey.D2

The character is however very different, it greatly depends on the active keyboard layout. A Northern American user presses Shift+2. A French user presses AltGr+0. A German user presses AltGr+Q. A Spanish user presses AltGr+2. Etcetera.

If you care only about the key then use ConsoleKeyInfo.Key, you do so for all non-typing keys like the function keys for example. Perhaps the typical gaming WASD keys. If you care only about the character, like @, then use ConsoleKeyInfo.KeyChar.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536