4

在我的 C#/WPF/.NET 4.5 应用程序中,我试图通过 KeyEventHandler 捕获按键,然后使用出色的Windows 输入模拟器来模拟该按键(将手势、语音等命令映射到键盘)。

麻烦的是,我从's中得到了一个Key枚举成员,但后来我需要传递一个to 。KeyEventHandlerRoutedEventArgsVirtualKeyCodeSimulateKeyPress()

我如何从KeyVirtualKeyCode

// 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);
}
4

1 回答 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方法返回的不是 aVirtualKeyCode而是int32必须转换为 a的 an VirtualKeyCode

于 2013-04-02T10:35:30.327 回答