How to hide the key pressed in a .NET console application

You probably know how to read the key pressed by the user in a .NET console application by the Console.ReadKey() method:

ConsoleKeyInfo pressedKey = Console.ReadKey();
Console.WriteLine("You have pressed: {0}", pressedKey.Key);

The above code will print the following if the user pressed ‘g’:

gYou have pressed: G

In other words ‘g’ will also be printed in the Console window. That’s expected as it is the normal behaviour of console applications. The user presses a key that produces some character, like the digit keys on the keyboard and it will be printed in the console window.

However, that’s not always what you’re intending to do. Sometimes you just want to collect a single character input from the user, and process that input in some way but not show it on the screen.

The solution is in fact very simple. Just use an overloaded version of ReadKey and pass in a “true” which means that you’d like to suppress the key being shown:

ConsoleKeyInfo pressedKey = Console.ReadKey(true);
Console.WriteLine("You have pressed: {0}", pressedKey.Key);

The new output will be:

You have pressed: G

…i.e. the initial ‘g’ won’t be show in the console.

View all various C# language feature related posts here.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: