How to warn the user if either CapsLock or NumLock are pressed in a .NET console application
September 21, 2016 Leave a comment
You’ve probably come across applications that warn you if the CapsLock button is pressed when typing a password. It’s a clever way to warn the user as passwords are normally not shown on the screen in plain text so it’s difficult to see what you’re typing. Similarly the NumLock button affects the behaviour of various keys on your keyboard.
Detecting whether those two special buttons are pressed is very simple in .NET console applications.
The following code sample will demonstrate both:
Console.Write("Your password please: "); if (Console.NumberLock) { Console.Write(" NumLock is on!!!! "); } if (Console.CapsLock) { Console.Write(" CapsLock is on!!!! "); }
If you run the above code with both CapsLock and NumLock turned on then you’ll get the following printed in the console window:
Your password please: NumLock is on!!!! CapsLock is on!!!!
View all various C# language feature related posts here.