Search code examples
c#.netcapslock

How can I find the state of NumLock, CapsLock and ScrollLock in .NET?


How can I find the state of NumLock, CapsLock and ScrollLock keys in .NET?


Solution

  • Import the WinAPI function GetKeyState:

    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
    public static extern short GetKeyState(int keyCode);
    

    And then you can use it like this:

    bool CapsLock = (((ushort)GetKeyState(0x14)) & 0xffff) != 0;
    bool NumLock = (((ushort)GetKeyState(0x90)) & 0xffff) != 0;
    bool ScrollLock = (((ushort)GetKeyState(0x91)) & 0xffff) != 0;
    

    It is for framework 1.1. For framework 2.0 (and later) you can use:

    Control.IsKeyLocked