Search code examples
c#.netwpfkeyboard

How to detect modifier key states in WPF?


Is there some global constructs that I can use whenever I need to access whether the Control, Shift, Alt buttons are down? For instance inside MouseDown event of a TreeView.

If so how?


Solution

  • 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 */ }