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
}
}
}