将 String 或 Char 转换为 Keys 对象
如果我使用以下代码:
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
Keys k = (Keys)(byte)c;
MessageBox.Show(c.ToString() + "|" + k.ToString());
}
我只能获得大写字母的正确转换。问题是,我还需要能够复制小写字符,但我在它们上遇到了转换错误。例如,“e”转换为“NumPad5”,其中“E”正确转换为“E”。我该如何攻击这个?我将获取输入字符串并为我正在尝试开发的宏播放器创建虚拟按键。
If I use the following code:
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
Keys k = (Keys)(byte)c;
MessageBox.Show(c.ToString() + "|" + k.ToString());
}
I can get a correct conversion for uppercase letters only. The problem is, I need to be able to replicate lower case characters as well, and I am getting conversion errors on them. For instance, 'e' converts to 'NumPad5', where 'E' converts correctly to 'E'. How do I attack this? I'm going to be taking input strings and creating virtual key presses for a macro player I am trying to develop.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这似乎是错误的做法。您是否考虑过使用SendKeys?
That seems like the wrong approach. Have you considered using SendKeys?
Keys
枚举并不是按下按键时生成的字符的字符值的直接副本。有时是,但有时不是。 中描述了每次按键的值编码方式文档:The
Keys
enumeration is not a straight copy of the character values of the character generated when the key is pressed. Sometimes it is, but sometimes it is not. The way the value is encoded for each keypress is described in the documentation:答案是为您需要的字符建立一个反向查找表。该代码可以进一步优化,但它是不言自明的。如果需要,您可以显式添加特殊字符。
如果您喜欢的话,您还可以同时构建一本字典,以另一种方式进行。多键字符需要一个简单的扩展,但无论如何它们不会直接映射到键。
如果您需要的话,请仔细阅读和可能的扩展:
The answer is to build a reverse lookup table for the chars you need. The code could be optimized further but it is self explanatory. You could add special chars explicitly if needed.
You could also simultaneously build a dictionary to go the other way also should it take your fancy. Multi-key chars would require a trivial extension but they don't map directly to Keys anyway.
For your perusal and possible extension should you require it: