Wasif Ale Wasif Ale -3 years ago 130
C# Question

How can I get the key pressed without hitting enter in c#?

How can I get the key pressed by user without hitting the enter key in C# ?

I want to get input from console but the point is the the every key pressed must be stored in a variable as soon as the key is pressed.

So I don't need to press ENTER key to submit the input.

Just like

getch()
does in C++.

Answer Source

Assuming you are referring to a console application this snippet will show all the keys pressed by a user until they hit enter to finish execution:

public class Program
{
    public static void Main()
    {

        ConsoleKeyInfo keyinfo;
        do
        {
            keyinfo = Console.ReadKey();
            Console.WriteLine(keyinfo.Key + " was pressed");
        }
        while (keyinfo.Key != ConsoleKey.Enter);
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download