c# – 将密钥转换为VirtualKeyCode
发布时间:2020-12-16 01:54:03 所属栏目:百科 来源:网络整理
导读:在我的C#/ WPF / .NET 4.5应用程序中,我试图通过KeyEventHandler捕获按键,然后使用优秀的 Windows Input Simulator模拟按键(将手势,语音等命令映射到键盘). 麻烦的是,我从KeyEventHandler的RoutedEventArgs中获取Key枚举的成员,但后来我需要将VirtualKeyCode
在我的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); } 解决方法
似乎
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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |