none
Set num lock

    Question

  • Hi,

    I'm trying to set the status of the num lock on keyboards, but I'm having no luck with the following code:

    private const int NumLock = 0x90;

    [DllImport("user32.dll")]
    private static extern int SetKeyboardState(byte
    [] keyState);

    [DllImport("user32.dll")]
    private static extern int GetKeyboardState(ref byte
    keyState);

    private void SetNumLock(Boolean isOn)
    {
         byte[] keyState = new byte
    [256];
         GetKeyboardState(
    ref
    keyState[0]);
         if
    (isOn)
         {
              keyState[NumLock] = 1;
         }
         else
         {
              keyState[NumLock] = 0;
         }
         SetKeyboardState(keyState);

    }

    However, while GetKeyboardState gets the right state of the num lock, when I call SetKeyboardState, it doesn't throw any exceptions but neither does anything happen to the num lock!

    Any ideas?

    Thanks,

    Weiran.

    Saturday, July 22, 2006 5:03 PM

Answers

  • To quote the MSDN documentation on SetKeyboardState():

    Because the SetKeyboardState function alters the input state of the calling thread and not the global input state of the system, an application cannot use SetKeyboardState to set the NUM LOCK, CAPS LOCK, or SCROLL LOCK (or the Japanese KANA) indicator lights on the keyboard.

    Using keybd_event() would be one option for this.

    Saturday, July 22, 2006 5:26 PM

All replies