System.ConsoleKey Enumeration

Represents the console keys.

Namespace

System

Assembly

System.Runtime.dll

Syntax

public enum ConsoleKey

Remarks

The ConsoleKey enumeration is used to identify special keys on the keyboard, such as function keys, navigation keys, and modifier keys. It is typically used with methods like Console.ReadKey() to detect user input in console applications.

Each member of the ConsoleKey enumeration corresponds to a specific key on a standard keyboard. For example, ConsoleKey.Enter represents the Enter key, ConsoleKey.Escape represents the Escape key, and ConsoleKey.F1 represents the F1 function key.

When a key is pressed, the Console.ReadKey() method returns a ConsoleKeyInfo object, which contains both the character representation of the key (if any) and its corresponding ConsoleKey value.

Members

Example

The following C# code example demonstrates how to use the ConsoleKey enumeration to detect when the user presses the Escape key:

using System;

public class Example
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Press the Escape key to exit...");

        ConsoleKeyInfo keyInfo;
        do
        {
            keyInfo = Console.ReadKey(intercept: true); // Intercept prevents the key from being displayed
            if (keyInfo.Key == ConsoleKey.Escape)
            {
                Console.WriteLine("Escape key pressed. Exiting.");
            }
            else
            {
                Console.WriteLine($"Key pressed: {keyInfo.Key}, Character: {keyInfo.KeyChar}");
            }
        } while (keyInfo.Key != ConsoleKey.Escape);
    }
}

See Also