How can I convert 'System.Windows.Input.Key' to 'System.Windows.Forms.Keys'?

Viewed 22792

I'm developing application in WPF but some components are written using WinForms. I wan't these components to pull key gesture from WPF part and convert them to Keys enum (used in WinForms).

Is there a built in converter for that? (probably not) Do you know "easier than big switch case" method to do that?

4 Answers
Keys formsKey = ...;
Key wpfKey = ...;
wpfKey = KeyInterop.KeyFromVirtualKey((int)formsKey);
formsKey = (Keys)KeyInterop.VirtualKeyFromKey(wpfKey);

The KeyInterop class is the "key," plus the fact that the Windows Forms Keys enumeration has the same integer values as the Win 32 virtual key codes.

To convert the WPF Key enumeration to the corresponding WinForms Keys enumeration use the static member TryParse of the Enum class:

Enum.TryParse(wpfKeyEnum.ToString(), out System.Windows.Forms.Keys winFormsKeyEnum)

WPF modifiers (ModifierKeys enumeration) can be converted the same way except the Windows key. In contrast to the Windows.Input.ModifierKeys enumeration of WPF the Windows.Forms.Keys enumeration distinguishes between left and right Windows keys and defines corresponding LWin an RWin fields.

This conversion method works in both directions.

Example

The example converts the Key and ModifierKeys enumerations of a WPF key up event to the corresponding WinForms Keys enumeration.

From Windows.Input.Key To System.Windows.Forms.Keys

private void OnPreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{ 
  // Convert key
  if (Enum.TryParse(e.Key.ToString(), out System.Windows.Forms.Keys winFormsKey))
  {
    MessageBox.Show(winFormsKey + "=" + (int) winFormsKey); // A=65
  }
}

From Windows.Input.ModifierKeys To System.Windows.Forms.Keys

private void OnPreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{ 
  ModifierKeys modifiers = e.KeyboardDevice.Modifiers;

  IEnumerable<ModifierKeys> pressedModifierKeys  = Enum.GetValues(modifiers.GetType())
    .Cast<ModifierKeys>()
    .Where(modifiers.HasFlag);

  // The ModifierKeys enumeration has a FlagsAttribute attribute
  foreach (ModifierKeys modifier in pressedModifierKeys)
  {
    if (Enum.TryParse(modifier.ToString(), out System.Windows.Forms.Keys winFormsModifierKey))
    {
      MessageBox.Show(winFormsModifierKey + "=" + (int) winFormsModifierKey); // Alt=262144
    }
  }
}
Related