将Key转换为VirtualKeyCode
本文关键字:VirtualKeyCode 转换 Key | 更新日期: 2023-09-27 18:07:06
在我的c#/WPF/。我试图通过KeyEventHandler捕获按键,然后使用优秀的Windows输入模拟器来模拟该按键(将手势,语音等命令映射到键盘)。
问题是,我从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);
}
似乎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
,而是必须转换为VirtualKeyCode
的int32
。