NAVEEN CHOUDHARY | "Every person is a New door to a Different world."


How to check the status of CAPS / NUMLOCK status in C#.NET

+ No comment yet
There are two types of codes available in C#.NET for checking the status of CAPS Lock and
NUM Lock.
a. Unmanaged Code : The code written in conventional languages like C, C++, VC++ etc. This kind of code can be called in the Managed Environment like .NET, JRE etc.

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
public static extern short GetKeyState(int keyCode);
bool CapsLock = (((ushort)GetKeyState(0x14)) & 0xffff) != 0;
bool NumLock = (((ushort)GetKeyState(0x90)) & 0xffff) != 0;
bool ScrollLock = (((ushort)GetKeyState(0x91)) & 0xffff) != 0;
MessageBox.Show("Caps Lock is on: " + CapsLock.ToString());
MessageBox.Show("Num Lock is on: " + NumLock.ToString());
MessageBox.Show("Scroll Lock is on: " + ScrollLock.ToString());
b. Managed Code: Code which is managed by the Runtime environment. This type of code is
basically a wrapper to the API classes that the Operating System Provides.

The Console
This is a standard class within the System namespace.
It represents the standard input, output and error streams for console applications. If we wish to determine the status of Caps Lock key using console class we can use the code below:
if (Console.CapsLock)
{
Console.WriteLine("Caps Lock is on!");
}
Control class also includes a method IsKeyLocked which allows to determine whether keys such as Caps Lock are switched on or off.
if (Control.IsKeyLocked(Keys.CapsLock))
{
MessageBox.Show("Caps Lock is on!");
}
On the similar grounds we can check the status of num lock etc e.g. IsKeyLocked(Keys.NumLock)