Search code examples
c#consolekeyboard-events

How to detect "Enter" in C# console?


I'm fairly new to C#, and I would be happy if you could help me with this.

I'm trying to detect when the Enter key is pressed.

Console.Write("**Press Enter**" "to do this" or "**Press Esc**" "to do that");

We usually use the readline after that, but only if the user will write something.

This time I want to detect if the user has pressed Enter or Esc.


Solution

  • Try something like this:

    ConsoleKeyInfo cki = Console.ReadKey(true);
    
    switch (cki.Key)
    {
        case ConsoleKey.Enter:
            Console.WriteLine("Enter key has been pressed");
            break;
        case ConsoleKey.Escape:
            Console.WriteLine("Escape key has been pressed");
            break;
        default:
            Console.WriteLine("Please press Enter or Esc");
            break;
    }