将Key转换为VirtualKeyCode

本文关键字:VirtualKeyCode 转换 Key | 更新日期: 2023-09-27 18:07:06

在我的c#/WPF/。我试图通过KeyEventHandler捕获按键,然后使用优秀的Windows输入模拟器来模拟该按键(将手势,语音等命令映射到键盘)。

问题是,我从KeyEventHandlerRoutedEventArgs中获得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);
}

将Key转换为VirtualKeyCode

似乎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