将键转换为虚拟键码

4
在我的C#/WPF/.NET 4.5应用程序中,我正在尝试通过KeyEventHandler捕获按键,并稍后使用出色的Windows Input Simulator模拟该按键(将手势、语音等命令映射到键盘)。
问题是,我从KeyEventHandler的RoutedEventArgs中获取Key枚举的成员,但稍后我需要传递VirtualKeyCode给SimulateKeyPress()。
如何从Key转换到VirtualKeyCode?
// Trigger reader
private void Editor_CommandButton_Click(object sender, RoutedEventArgs e) {
  PressKeyModal.Visibility = System.Windows.Visibility.Visible;
  AddHandler(Keyboard.KeyDownEvent, (KeyEventHandler)Editor_HandleKeyDownEvent);
}
// Read key press from keyboard
private void Editor_HandleKeyDownEvent(object sender, KeyEventArgs e) {
  // Here is the culprit
  VirtualKeyCode CodeOfKeyToEmulate = ConvertSomehow(e.Key);
  // /culprit
  PressKeyModal.Visibility = System.Windows.Visibility.Hidden;
  RemoveHandler(Keyboard.KeyDownEvent, (KeyEventHandler)Editor_HandleKeyDownEvent);
}

// Later, emulate the key press
private void EmulateKeyPress(VirtualKeyCode codeOfKeyToEmulate( {
  InputSimulator.SimulateKeyPress(codeOfKeyToEmulate);
}

1
你使用的是哪个版本的.NET? - keyboardP
.NET 4.5 - mbaytas
1个回答

8

看起来KeyInterop.VirtualKeyFromKey方法是我要找的。因此,上面代码中麻烦的部分变成了:

// Read key press from keyboard
private void Editor_HandleKeyDownEvent(object sender, KeyEventArgs e) {
  // The rehabilitated culprit
  VirtualKeyCode CodeOfKeyToEmulate = (VirtualKeyCode)KeyInterop.VirtualKeyFromKey(e.Key);
  // /rehabilitated culprit
  PressKeyModal.Visibility = System.Windows.Visibility.Hidden;
  RemoveHandler(Keyboard.KeyDownEvent, (KeyEventHandler)Editor_HandleKeyDownEvent);
}

值得注意的是,KeyInterop.VirtualKeyFromKey 方法返回的不是 VirtualKeyCode,而是一个必须转换为 VirtualKeyCodeint32

感谢@keyboardP的回答。他最初建议使用KeyInterop.KeyFromVirtualKey方法,这不是我要找的,但他引导了我走向正确的方向(KeyInterop类)。 - mbaytas
复制了 MSDN 页面上错误的链接,但很高兴你解决了问题。别忘了在几天后接受你的答案 :) - keyboardP
@keyboardP 如果你的第二个答案还在,我会接受它的 =) 非常感谢你的帮助。 - mbaytas

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