Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
}
like image 828
ThickBook Avatar asked Jun 18 '10 08:06

ThickBook


People also ask

What is console read key?

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

What does console ReadLine do?

The Console. ReadLine() method in C# is used to read the next line of characters from the standard input stream.

What are console keys?

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.

How do I get a keystroke in Python?

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.


2 Answers

Try

Console.WriteLine("Enter any Key: ");
ConsoleKeyInfo name = Console.ReadKey();
Console.WriteLine("You pressed {0}", name.KeyChar);
like image 126
harriyott Avatar answered Oct 24 '22 11:10

harriyott


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()
like image 21
Tomas Aschan Avatar answered Oct 24 '22 13:10

Tomas Aschan