Search code examples
c#console-applicationkeyevent

C# console key press event


I just started to learn c# console events.

Is there a possible way that a c# application will automatically jump into a new command by just pressing a letter.

I have this mini code below.

I was developing a mini text base base.

I just used the Console.Read(); so the user will type the letter Y then he still needs to press the enter key what I wanted is, if the user will press "y" or anykey into the keyboard the statement goes to the if statement.

Is it possible.

        Console.Write("Press Y to start the game.");

        char theKey = (char) Console.Read();


        if (theKey == 'y' || theKey == 'Y')
        {
            Console.Clear();
            Console.Write("Hello");
            Console.ReadKey();
        }
        else
            Console.Write("Error");

Solution

  • You should use ReadKey method (msdn):

    Console.Write("Press Y to start the game.");
    
    char theKey = Console.ReadKey().KeyChar;
    
    if (theKey == 'y' || theKey == 'Y')
    {
        Console.Clear();
        Console.Write("Hello");
        Console.ReadKey();
    }
    else
        Console.Write("Error");
    

    The return value of ReadKey method is ConsoleKey enum so you can use it in the if condition:

    Console.Write("Press Y to start the game.");
    
    ConsoleKey consoleKey = Console.ReadKey().Key;
    
    if (consoleKey == ConsoleKey.Y)
    {
        Console.Clear();
        Console.Write("Hello");
        Console.ReadKey();
    }
    else
        Console.Write("Error");