C# 将密钥转换为VirtualKeyCode

C# 将密钥转换为VirtualKeyCode,c#,wpf,.net-4.5,keyboard-events,C#,Wpf,.net 4.5,Keyboard Events,在我的C#/WPF/.NET 4.5应用程序中,我试图通过KeyEventHandler捕捉按键,然后使用优秀的来模拟按键(将手势、语音等命令映射到键盘) 问题是,我从KeyEventHandler的RoutedEventTargets中获得了Key枚举的一个成员,但稍后我需要将VirtualKeyCode传递到SimulateKeyPress() 如何从键转到VirtualKeyCode // Trigger reader private void Editor_CommandButton_C

在我的C#/WPF/.NET 4.5应用程序中,我试图通过KeyEventHandler捕捉按键,然后使用优秀的来模拟按键(将手势、语音等命令映射到键盘)

问题是,我从
KeyEventHandler
RoutedEventTargets
中获得了
Key
枚举的一个成员,但稍后我需要将
VirtualKeyCode
传递到
SimulateKeyPress()

如何从
转到
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);
}
看来这个方法正是我想要的。因此,上述代码中的麻烦部分变成:

// 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
,而是一个
int32
,它必须转换成
VirtualKeyCode
,您使用的是.NET的哪个版本?.NET4.5(相应编辑的问题),感谢@keyboardP的回答。他最初提出了这个方法,这不是我想要的,但他引导我走向了正确的方向(类)。从MSDN页面复制了错误的链接,但很高兴你把它整理好了。别忘了在几天后接受你的答案:)@keyboard如果你的第二个答案还在的话,我会接受的=)谢谢你的帮助。