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.

Advertisement

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:

WordPress.com Logo

You are commenting using your WordPress.com 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

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

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

%d bloggers like this: