How to hide the key pressed in a .NET console application
June 15, 2017 Leave a comment
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.