tags:

views:

421

answers:

5

Hello,

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

A: 

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.

Reed Copsey
A: 

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

Thomas Levesque
That just checks it, but doesn't tell you WHEN it changes. To detect the action of the user changing the num lock key requires a low level keyboard hook
Reed Copsey
A: 

May be you will find useful information from this link - http://www.codeproject.com/KB/statusbar/update_toggle_key_status.aspx

adatapost
A: 

See this link

http://stackoverflow.com/questions/938144/detect-if-numlock-is-off-and-turn-it-always-back-on

The code is in vb.net but can be easily translated to c#.

Bye.

RRUZ
A: 

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;
        }
    }
}
Cecil Has a Name