C# Console.CapsLock Property

Console screenshot

Is the caps lock key enabled? You want to check in your C# console program. With the Console.CapsLock property, you can determine this and provide an error message or change some logic in your program.

This C# example program introduces the Console.CapsLock property.

Example

This program simply prints the value returned by Console.CapsLock every one second. When you execute it, try pressing the caps lock key. It will start printing True when the key is pressed.

Sleep Method Pauses Programs Console.WriteLine
Program that uses Console.CapsLock property [C#]

using System;
using System.Threading;

class Program
{
    static void Main()
    {
	while (true)
	{
	    Thread.Sleep(1000);
	    bool capsLock = Console.CapsLock;
	    Console.WriteLine(capsLock);
	}
    }
}

Output

False
False
True
True
True
False
True
True

Uses

Programming tip

The Console.CapsLock property could be used in several different ways. If a program is requiring a password to be entered, you could print an error message if caps lock is pressed and the password is incorrect. You could even add a separate "mode" in your program depending on whether caps lock is pressed; this would need to be documented.

Summary

The C# programming language

With Console.CapsLock, you can detect whether caps lock is enabled on the computer. This property cannot be assigned; if you need to turn caps lock off, you will need to instruct the keyboard user to press it again.

Console Programs
.NET