Search code examples
c#winformssendkeyskeystrokenumpad

How do you send NumPad keys using SendKeys?


I want to send the keystroke of NumPad keys (1-9).

I tried to use:

SendKeys.SendWait("{NUMPAD1}");

but it says

System.ArgumentException: The keyword NUMPAD1 is invalid (translated)

So i don't know the right keycode for the NumPad.


Solution

  • Out of curiosity I looked at the source code for SendKeys. There's nothing explaining why the numpad codes were excluded. I wouldn't recommend this as a preferred option, but it's possible to add the missing codes to the class using reflection:

    FieldInfo info = typeof(SendKeys).GetField("keywords",
        BindingFlags.Static | BindingFlags.NonPublic);
    Array oldKeys = (Array)info.GetValue(null);
    Type elementType = oldKeys.GetType().GetElementType();
    Array newKeys = Array.CreateInstance(elementType, oldKeys.Length + 10);
    Array.Copy(oldKeys, newKeys, oldKeys.Length);
    for (int i = 0; i < 10; i++) {
        var newItem = Activator.CreateInstance(elementType, "NUM" + i, (int)Keys.NumPad0 + i);
        newKeys.SetValue(newItem, oldKeys.Length + i);
    }
    info.SetValue(null, newKeys);
    

    Now I can use eg. SendKeys.Send("{NUM3}"). It doesn't seem to work for sending alt codes however, so maybe that's why they left them out.