Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read in a single keyboard character (like getch)?

Tags:

c#

input

getch

In C, I could use getch() for getting an input without having the user to press enter. e.g.

#include <conio.h>

int main()
{
    char c;
    c = getch();
    return 0;
}

What function can do the same in C#? (without pressing enter).

like image 205
alextikh Avatar asked Mar 01 '14 09:03

alextikh


3 Answers

You can use Console.ReadKey():

Obtains the next character or function key pressed by the user.

It returns information about pressed key. Then you can use KeyChar property to get Unicode character of pressed key:

int Main()
{
    char c = Console.ReadKey().KeyChar;
    return 0;
}
like image 200
Sergey Berezovskiy Avatar answered Oct 20 '22 00:10

Sergey Berezovskiy


You can use Console.ReadKey().KeyChar to Read the character from the Console without pressing Enter key

From MSDN:

Obtains the next character or function key pressed by the user. The pressed key is displayed in the console window.

Try This:

char ch=Console.ReadKey().KeyChar;
like image 3
Sudhakar Tillapudi Avatar answered Oct 20 '22 00:10

Sudhakar Tillapudi


getch();

does not show the input in the console.

Therefore you need this in C#

char ch = Console.ReadKey(true).KeyChar;

if you need the input display at console then this you need

char ch1 = Console.ReadKey(false).KeyChar;
like image 3
V-SHY Avatar answered Oct 20 '22 00:10

V-SHY