43

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
  • 6,138
  • 12
  • 49
  • 61
rem
  • 16,745
  • 37
  • 112
  • 180

4 Answers4

68
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
  • 6,138
  • 12
  • 49
  • 61
Stanislav Kniazev
  • 5,386
  • 3
  • 35
  • 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
  • 3,009
  • 3
  • 23
  • 18
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
  • This code returns true if Ctrl+Shift (or Ctrl+Alt) is pressed. This may or may not be the intended result. If the intention is to handle the exact Ctrl+ combination, then the equals operator is the way to go. – Mustafa Özçetin Mar 10 '23 at 14:13
0

As Grzegorz Godlewski said above, Keyboard.Modifiers.HasFlag(ModifierKey.Control) can be used.

Although @l33t points out it is not very performant, in the comment it appears there have been improvements in the performance of HasFlag in .NET 4.5/4.6. (see benchmarks results in What is it that makes Enum.HasFlag so slow? and the comments below, and also in this answer).

But still nothing as fast as doing a native check (i.e. flagsToCheck & flag != 0 ) judging by the conclusion here.

David Gomes
  • 650
  • 2
  • 10
  • 34
beechio
  • 31
  • 4