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 )

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s


A great site

Elliot Balynn's Blog

A directory of wonderful thoughts

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: