#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

#971 – Reading a Line of Input from the Console

For testing purposes, you may create a simple console application that allows writing to and reading from a console window.

The Console.ReadLine method reads the next line’s worth of characters, storing the result in a string.  The user can enter some text and then press the Enter key.  When the user presses Enter, whatever they typed on that line is stored in a variable of type string.

            while (true)
            {
                Console.Write(": ");
                string nextLine = Console.ReadLine();

                Console.WriteLine("[{0}]", nextLine);
            }

971-001

You can also use the Console.Read method to read a single character. The characters are not read until the user presses Enter.

In the example below, the user types the letters a, and and then presses Enter.  The two calls to Console.Read are then executed, storing the ASCII values of the characters entered.

            int char1 = Console.Read();
            int char2 = Console.Read();

            Console.Write("{0} {1}",
                char1.ToString(),
                char2.ToString());

971-002

#7 – Reading and Writing from the Console

To read and write from the console, use Console.Read, Console.ReadLine, Console.Write, Console.WriteLine.

namespace ReadWriteConsole
{
    class Program
    {
        static void Main()
        {
            Console.Write("This ");
            Console.WriteLine("is all on one line.");
            Console.Write("Enter your name: ");
            string name = Console.ReadLine();
            Console.WriteLine(name);
            Console.Read();     // pause
        }
    }
}