Disabling num-lock toggle in C#?

4.2k views Asked by At

I would like to maintain num-lock ON as long as my application is running, so that if the user un-toggles num-lock, it will immediately be toggled back on. What's the simplest way to achieve that in C#?

To clarify, while my application is running I "own" the user's machine, so in my specific case there will not be a need for the user to un-toggle num-lock (that does not mean I have focus at all times).

Thanks

3

There are 3 answers

0
Reed Copsey On

You need to add a low level keyboard hook to do this. Stephen Toub wrote a tutorial on his blog on setting this up.

Your keyboard hook can check the status of VK_NUMLOCK. For a VB example see here.

1
Thomas Levesque On

You can do it with a few P/Invoke calls. Check out this page

0
Cecil Has a Name On

Enable Form.KeyPreview on your form, add a reference to Microsoft.VisualBasic (or you can use the native API directly to poll the state of the num lock key).

public static class NativeMethods
{
    public const byte VK_NUMLOCK = 0x90;
    public const uint KEYEVENTF_EXTENDEDKEY = 1;
    public const int KEYEVENTF_KEYUP = 0x2;

    [DllImport("user32.dll")]
    public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);

    public static void SimulateKeyPress(byte keyCode)
    {
        keybd_event(VK_NUMLOCK, 0x45, KEYEVENTF_EXTENDEDKEY, 0);
        keybd_event(VK_NUMLOCK, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
    }
}

public partial class Form1 : Form
{
    private bool protectKeys; // To protect from inifite keypress chain reactions

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (protectKeys)
            return;

        if (e.KeyCode == Keys.NumLock && 
            !(new Microsoft.VisualBasic.Devices.Keyboard().NumLock))
        {
            protectKeys = true;
            NativeMethods.SimulateKeyPress(NativeMethods.VK_NUMLOCK);
            protectKeys = false;
        }
    }
}