0

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

I'm trying to detect the enter Key when 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.

Can You help me? is this possible in C#? Thanksss

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
  • I think [this question](http://stackoverflow.com/questions/8898182/how-to-handle-key-press-event-in-console-application) might be a better dupe target as it's specifically about console applications, where you can't really do keypress detection – James Thorpe Oct 19 '15 at 08:32
  • The linked duplicate question is about Winforms and is not applicable for console applications. – sara Oct 19 '15 at 08:34

1 Answers1

4

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;
}
w.b
  • 11,026
  • 5
  • 30
  • 49