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)
{
...
}
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");
}
}
If you want to detect modifiers only, you can also use:
if (Keyboard.Modifiers == ModifierKeys.Control) {}
if (Keyboard.Modifiers == ModifierKeys.Shift) {}
etc. More here.
In .NET 4.0 you could use:
Keyboard.Modifiers.HasFlag(ModifierKeys.Control)
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.