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);
}
}
ReadKey() Method makes the program wait for a key press and it prevents the screen until a key is pressed. In short, it obtains the next character or any key pressed by the user. The pressed key is displayed in the console window(if any input process will happen).
The Console. ReadLine() method in C# is used to read the next line of characters from the standard input stream.
The console is normally accessed by pressing the backtick key ` (frequently also called the ~ key; normally located below the ESC key) on QWERTY keyboards or the ² on AZERTY keyboards, and is usually hidden by default.
You can install the keyboard module in your machine using PIP as follows. To detect keypress, we will use the is_pressed() function defined in the keyboard module. The is_pressed() takes a character as input and returns True if the key with the same character is pressed on the keyboard.
Try
Console.WriteLine("Enter any Key: ");
ConsoleKeyInfo name = Console.ReadKey();
Console.WriteLine("You pressed {0}", name.KeyChar);
Console.Read()
reacts when the user presses Enter, and returns the entire string that the user typed before pressing Enter. To read one keystroke, use
Console.ReadKey()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With