Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Key to VirtualKeyCode

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);
}
like image 500
mbaytas Avatar asked Feb 16 '23 23:02

mbaytas


1 Answers

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.

like image 104
mbaytas Avatar answered Feb 27 '23 02:02

mbaytas