Using ReadKey( )

The .NET Framework includes a method in Console that enables you to read individual keystrokes directly from the keyboard, in a non-line-buffered manner. This method is called ReadKey( ). When it is called, it waits until a key is pressed. When a key is pressed, ReadKey( ) returns the keystroke immediately. The user does not need to press enter. Thus, ReadKey( ) allows keystrokes to be read and processed in real time.

ReadKey( ) has these two forms:

static ConsoleKeyInfo ReadKey( )
static ConsoleKeyInfo ReadKey(bool intercept)

The first form waits for a key to be pressed. When that occurs, it returns the key and also displays the key on the screen. The second form also waits for and returns a keypress. However, if intercept is true, then the key is not displayed. If intercept is false, the key is displayed.

ReadKey( ) returns information about the keypress in an object of type ConsoleKeyInfo, which is a structure. It contains the following read-only properties:

char KeyChar
ConsoleKey Key
ConsoleModifi ers Modifi ers

KeyChar contains the char equivalent of the character that was pressed. Key contains a value from the ConsoleKey enumeration, which is an enumeration of all the keys on the keyboard. Modifiers describes which, if any, of the keyboard modifiers atl, ctrl, or shift were pressed when the keystroke was generated. These modifiers are represented by the ConsoleModifiers enumeration, which has these values: Control, Shift, and Alt. More than one modifier value might be present in Modifiers.
The major advantage to ReadKey( ) is that it provides a means of achieving interactive keyboard input because it is not line buffered. To see this effect, try the following program:


using System;

namespace ConsoleApplication1
    class ReadKeys
        static void Main()
            ConsoleKeyInfo keypress;
            Console.WriteLine("Enter keystrokes. Enter Q to stop.");
                keypress = Console.ReadKey(); // read keystrokes
                Console.WriteLine(" Your key is: " + keypress.KeyChar);
                // Check for modifier keys.
                if ((ConsoleModifiers.Alt & keypress.Modifiers) != 0)
                    Console.WriteLine("Alt key pressed.");
                if ((ConsoleModifiers.Control & keypress.Modifiers) != 0)
                    Console.WriteLine("Control key pressed.");
                if ((ConsoleModifiers.Shift & keypress.Modifiers) != 0)
                    Console.WriteLine("Shift key pressed.");
            } while (keypress.KeyChar != 'Q');

You may also like...