#972 – Reading Keystrokes from the Console

The Console.Read method reads input from a console window one character at a time but does not begin reading characters until after the user has pressed Enter.

The Console.ReadKey method, on the other hand, reads a key that the user presses immediately, without waiting for the user to press Enter.  The ReadKey method returns a value whose type is ConsoleKeyInfo, which contains fields that tell you which key was pressed:

  • Key field – ConsoleKey (enumeration) value indicating the exact key that was pressed
  • KeyChar field – Unicode character (of type char) for the key that was pressed

In the example below, we read two keypresses before displaying what was entered.  Notice that the output is shown after we enter two characters, but before we’ve pressed the Enter key.

            ConsoleKeyInfo cki1 = Console.ReadKey();
            ConsoleKeyInfo cki2 = Console.ReadKey();

            Console.Write("[{0},{1}]",
                cki1.KeyChar,
                cki2.KeyChar);

972-001

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: