-1

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...

4
  • 1
    Look into using Console.ReadKey. It returns a ConsoleKey which you could then check if it is "Enter" Commented Jan 23, 2021 at 20:45
  • Many thanks - I did try that as well. But I struggle with the part of identify the specific key "ENTER"... Commented Jan 23, 2021 at 20:48
  • if(Console.ReadKey() == ConsoleKey.Enter) Commented Jan 23, 2021 at 20:50
  • 1
    duplicate Detecting key presses in console Commented Jan 23, 2021 at 20:57

1 Answer 1

0

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");
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow! many thanks to all of you... super simple...! take care guys...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.