ConsoleKeyInfo, question mark and portability

I have a small C # console application that reads a key and checks if the key was a question mark:

ConsoleKeyInfo ki = System.Console.ReadKey(); if (ki.ConsoleKey.Oem2) // Do something 

I came to Oem2 when I saw what value was really assigned in the debugger, because there is no console code for the question mark > .

Now I could use ki.KeyChar instead, but the application should also respond to certain keys (e.g. media keys) that do not map to characters. To determine which key was actually pressed, implicitly check both ConsoleKey and KeyChar . On the other hand, don't rely on Oem2 to always display on ? in all circumstances and regions.

Is it better to check both properties to determine which key was pressed?

Any insight into why ConsoleKeyInfo was designed this way is appreciated.

+8
c # console-application
source share
3 answers

In this case, you will need to check KeyChar == '?' . From MSDN :

OEM2: OEM 2 key (OEM specific).

So, you are just lucky to have this on your equipment ? .

The ConsoleKeyInfo structure provides a KeyChar ( Char value) as well as Modifiers (enumeration) to help you decide which keys the user clicked.

+6
source share

I think you should think about what happens when someone has a different keyboard layout.

If you want to check the "question mark key on my computer", use ConsoleKey . But this is probably not a good idea, and you should probably stick with user preferences and use KeyChar .

But for keys that don't map to characters (and the user cannot reassign them using a different keyboard layout), you should use ConsoleKey .

So yes, I think you should check both properties in this case.

+2
source share

I assume the reason for this design is that Console.ReadKey() relies on a native function ( ReadConsoleInput ) that returns an array KEY_EVENT_RECORD in case of a key press, where each key event has an ASCII / Unicode character representation and virtual key code . Pay attention to VK_OEM_2 in my previous link - this is the value of ConsoleKey.Oem2 .

+2
source share

All Articles