Search code examples
c#loopsif-statementconsole-output

Check if user pressed Enter


the following scenario is given:

Welcome screen appears. If user has read the welcome text he has 2 choices:

a) pressing ENTER to continue an getting the next text

b) pressing the E-Key in oder to leave the program

So my problem is:

how can I check if the user pressed the ENTER-Key?

what i tried so far - just as very primitive prototype

...var userInput= Console.ReadLine();

    if (userInput == "\r")
    {
        Console.WriteLine("correct");
    }
    else
    {
        Console.WriteLine("wrong");
    }....

I also tried it via Regex but I didn't make it run. Thanks for helping...


Solution

  • Just like this (with Console.ReadKey):

    static void Main(string[] args)
    {
        Console.WriteLine("Hello Mr.Sun! Try press enter now:");
        var userInput = Console.ReadKey();
        if(userInput.Key == ConsoleKey.Enter)
        {
            Console.WriteLine("You pressed enter!");
        } else
        {
            Console.WriteLine("You pressed something else");
        }
    }