ThickBook ThickBook - 1 month ago 9
C# Question

How to read a key pressed by the user and display it on the console?

I am trying to ask user "enter any key" and when that key is pressed it shows that "You Pressed 'Key'". Can you help what's wrong in this code?

This is what I have written:

using System;
class Program
{
public static void Main(string[] args)
{
Console.Write("Enter any Key: ");
char name = Console.Read();
Console.WriteLine("You pressed {0}", name);
}
}

Answer

Try

Console.WriteLine("Enter any Key: ");
ConsoleKeyInfo name = Console.ReadKey();
Console.WriteLine("You pressed {0}", name.KeyChar);