C# Console.NumberLock Property

Console screenshot

How can you detect the Num Lock key in your C# console application? With the Console.NumberLock property, you can determine if the key is pressed, and display an error or change behavior as necessary.

Example

This program introduces a simple loop where the current value of the Console.NumberLock property is printed to the console every one second. As this program executes, you can press Num Lock and the output of the program will change.

This C# program uses the Console.NumberLock method. It detects Num Lock.

Program that uses Console.NumberLock [C#]

using System;
using System.Threading;

class Program
{
    static void Main()
    {
	while (true)
	{
	    Console.WriteLine(Console.NumberLock);
	    Thread.Sleep(1000);
	}
    }
}

Output

False
False
True
True
False
False
Programming tip

Set NumberLock. You cannot set the value of the Console.NumberLock property. If you do not want the key pressed, you must tell the user to press it again. On most keyboards, a light will glow if the Num Lock key is pressed.

Summary

The Console.NumberLock property, like the Console.CapsLock property, provides a way to determine if a keyboard key is pressed. In some programs, the Num Lock key is used to change the keyboard mode and the program's response to key presses.

Console Programs
.NET