In my C#/WPF/.NET 4.5 application I am trying to capture a key press via a KeyEventHandler, and later use the excellent Windows Input Simulator to emulate that key press (to map gesture, voice etc. commands to a keyboard).
The trouble is, I get a member of the Key
enumeration from the KeyEventHandler
's RoutedEventArgs
, but later I need to pass a VirtualKeyCode
to SimulateKeyPress()
.
How do I go from Key
to 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);
}
It appears that the KeyInterop.VirtualKeyFromKey method is what I was looking for. The troublesome section in the code above thus becomes:
// 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);
}
It's worth noting that the KeyInterop.VirtualKeyFromKey
method returns not a VirtualKeyCode
but an int32
which has to be cast into a VirtualKeyCode
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With