How to warn the user if either CapsLock or NumLock are pressed in a .NET console application

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.

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

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

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