Extracting information about key pressed in .NET console applications

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.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

2 Responses to Extracting information about key pressed in .NET console applications

  1. Vikram says:

    Thanks a lot for the nice post. Very useful information.

  2. stephen coleby says:

    These c# short code snippets are very very useful for anyone learning the language. Thanks.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: