In order to know whether or not Caps Lock, Num Lock or Scroll Lock keys are on, we need to make use of the Win32 API through a call to an unmanaged function.
Since we’ll make a call to an unmanaged function, the following using statement is in order:
using System.Runtime.InteropServices;
The following is the definition for the unmanaged function we’ll be using, GetKeyState():
// An umanaged function that retrieves the states of each key
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
public static extern short GetKeyState(int keyCode);
And finally we retrieve the state of each of the three keys and show it in a message box:
// Get they key state and store it as bool
bool CapsLock = (((ushort)GetKeyState(0x14)) & 0xffff) != 0;
bool NumLock = (((ushort)GetKeyState(0x90)) & 0xffff) != 0;
bool ScrollLock = (((ushort)GetKeyState(0x91)) & 0xffff) != 0;
// Show the status
MessageBox.Show("Caps Lock is on: " + CapsLock.ToString());
MessageBox.Show("Num Lock is on: " + NumLock.ToString());
MessageBox.Show("Scroll Lock is on: " + ScrollLock.ToString());
Here is the complete source code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace Labs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// An umanaged function that retrieves the states of each key
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
public static extern short GetKeyState(int keyCode);
private void Form1_Load(object sender, EventArgs e)
{
// Get they key state and store it as bool
bool CapsLock = (((ushort)GetKeyState(0x14)) & 0xffff) != 0;
bool NumLock = (((ushort)GetKeyState(0x90)) & 0xffff) != 0;
bool ScrollLock = (((ushort)GetKeyState(0x91)) & 0xffff) != 0;
// Show the status
MessageBox.Show("Caps Lock is on: " + CapsLock.ToString());
MessageBox.Show("Num Lock is on: " + NumLock.ToString());
MessageBox.Show("Scroll Lock is on: " + ScrollLock.ToString());
}
}
}