#645 – Checking for the Presence of Modifier Keys
September 12, 2012 3 Comments
In Windows, a modifier key is a key that you press in combination with another key. The standard modifier keys in Windows are:
- Alt key
- Control (Ctrl) key
- Shift key
- Windows key (Windows logo on face of key)
In a WPF keypress handler (PreviewKeyDown, KeyDown, PreviewKeyUp and KeyUp), you can check for the presence of one of the modifier keys using the KeyEventArgs.KeyboardDevice.Modifiers property. This property is an enumerated type that is a bitwise combination of the possible values. You can check for the presence of one of the modifiers by doing an AND operation against the modifier.
private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e) { Trace.WriteLine(string.Format("----- PreviewKeyDown for key {0}", e.Key)); // Dumping out all modifiers Trace.WriteLine(string.Format(" KeyboardDevice.Modifiers = {0}", e.KeyboardDevice.Modifiers); // Checking for specific modifiers if ((e.KeyboardDevice.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt) Trace.WriteLine(" Alt key !"); if ((e.KeyboardDevice.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) Trace.WriteLine(" Ctrl key !"); }