如何使用SendKeys发送NumPad键?

4

我希望发送NumPad键(1-9)的按键。

我尝试使用以下方法:

SendKeys.SendWait("{NUMPAD1}");

但是它报错说:

System.ArgumentException: 关键字 NUMPAD1 无效

所以我不知道NumPad的正确按键码。


阅读了这个链接,看起来似乎不可能... - Mischa
2个回答

4

出于好奇,我查看了SendKeys的源代码。没有任何内容解释为什么数字键盘代码被排除在外。我不建议这作为首选选项,但可以使用反射将缺失的代码添加到类中:

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);

现在我可以使用例如SendKeys.Send("{NUM3}")。然而,似乎无法发送alt代码,所以可能这就是为什么他们省略了它们的原因。

如何使用反射向源代码添加内容? - Bedir
@Bedir 如果你的意思是添加到/替换无法通过继承重写的现有.NET方法,我不确定。这个问题的答案可能会对你有所帮助。 - Bloopy
可以确认,对于使用alt代码,这不幸地不起作用。 - Philipp

0

您应该能够像传递字母一样传递数字。例如:

SendKeys.SendWait("{A}");  //sends the letter 'A'
SendKeys.SendWait("{5}");  //sends the number '5'

我知道,那是基础内容。我需要的是数字键盘上的数字,而不是普通的数字。 - Regster Up
当然有区别,在几乎每个游戏中的控制配置中,您都可以使用数字键盘进行控制,并且数字键有自己的名称(例如NUM_4),在按下时显示在设置中。这对键盘顶部的数字没有影响。 - Regster Up
1
它们似乎映射到相同的字符代码。 ConsoleKeyInfo c1 = Console.ReadKey(true);Console.WriteLine(c1.Key); Console.WriteLine(c1.KeyChar); Console.WriteLine((int)c1.KeyChar);ConsoleKeyInfo c2 = Console.ReadKey(true);Console.WriteLine(c2.Key); Console.WriteLine(c2.KeyChar); Console.WriteLine((int)c2.KeyChar); 如果这有帮助的话,通过Windows API看起来是可能的http://www.vbforums.com/showthread.php?347527-Using-SendKeys-to-Send-Number-Pad-Numbers - John Smith
非常有帮助,这对我很有帮助。 - Regster Up

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接