How to detect modifier key states in WPF? How to detect modifier key states in WPF? wpf wpf

How to detect modifier key states in WPF?


Use class Keyboard. Using Keyboard.IsKeyDown you can check if Control, Shift, Alt is down now.

For Shift:

if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)){ /* Your code */ }

For Control:

if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)){ /* Your code */ }

For Alt:

if (Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt)){ /* Your code */ }


There's also:

// Have to get this value before opening a dialog, or user will have released the control keyif ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control){}


    private bool IsShiftKey { get; set; }    private void OnPreviewKeyDown(object sender, KeyEventArgs e)    {        IsShiftKey = Keyboard.Modifiers == ModifierKeys.Shift ? true : false;        if ((Key.Oem3 == e.Key || ((IsShiftKey && Key.Oem4 == e.Key) || (IsShiftKey && Key.Oem6 == e.Key) || (IsShiftKey && Key.Oem5 == e.Key)) && (validatorDefn as FormatValidatorDefinition).format == "packedascii"))        {           e.Handled = true;        }    }