Extracting information about key pressed in .NET console applications
March 23, 2016 2 Comments
Console applications let you extract the key(s) pressed by the user using the Console.ReadKey() method. It returns an object of type ConsoleKeyInfo which includes a number of useful properties.
ConsoleKeyInfo has the following properties:
- Key: returns an enumeration of type ConsoleKey. Examples include ConsoleKey.A, ConsoleKey.PrintScreen, ConsoleKey.Help etc., i.e. there’s an entry for each key on a keyboard. There are more than 240 values in this enumeration.
- KeyChar: same as the above but it returns the key pressed as a char where it makes sense. E.g. F11 is not associated with a character, KeyChar will be an empty character ‘\0’. Also, if the combined value of the keys pressed produces whitespace or an empty character then KeyChar will be ‘\0’. Example: ctrl+alt+s
- Modifiers: returns an enumeration of type ConsoleModifiers which holds the values for the Alt, Shift and Control keys
The following code sample prints each of these properties:
static void Main(string[] args) { RunPressKeyCodeSample(); } private static void RunPressKeyCodeSample() { ConsoleKeyInfo keyInfo = Console.ReadKey(); ConsoleKey keyPressed = keyInfo.Key; Debug.WriteLine("Key pressed: {0}", keyPressed); char keyChar = keyInfo.KeyChar; Debug.WriteLine("Char format: {0}", keyChar); ConsoleModifiers modifiers = keyInfo.Modifiers; Debug.WriteLine("Any modifiers: {0}", modifiers); }
Here’s an example output when ctrl+shift+F11 are pressed:
Key pressed: F11
Char format:
Any modifiers: Shift, Control
Here comes another example when shift+p are pressed:
Key pressed: P
Char format: P
Any modifiers: Shift
View all various C# language feature related posts here.
Thanks a lot for the nice post. Very useful information.
These c# short code snippets are very very useful for anyone learning the language. Thanks.