41

How I can add an additional condition for a certain keyboard key, to a WPF MouseLeftButtonDown event-handler?

For example Ctrl + key

private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{         
    ...
}
Ivar
  • 5,377
  • 12
  • 50
  • 56
rem
  • 16,105
  • 37
  • 108
  • 179

3 Answers3

64
private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
    if(Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) {
        MessageBox.Show("Control key is down");
    } else {
        MessageBox.Show("Control key is up");
    }
}
Ivar
  • 5,377
  • 12
  • 50
  • 56
Stanislav Kniazev
  • 5,220
  • 3
  • 34
  • 44
42

If you want to detect modifiers only, you can also use:

if (Keyboard.Modifiers == ModifierKeys.Control) {}
if (Keyboard.Modifiers == ModifierKeys.Shift) {}

etc. More here.

742
  • 2,959
  • 3
  • 22
  • 16
14

In .NET 4.0 you could use:

Keyboard.Modifiers.HasFlag(ModifierKeys.Control)
  • Be careful though. You don't want `HasFlag()` on a hot path. On .NET Framework, it produces garbage on each run. See [this answer](https://stackoverflow.com/questions/11665279/why-enums-hasflag-method-need-boxing). – l33t May 03 '21 at 12:11