简体   繁体   中英

Ctrl key press condition in WPF MouseLeftButtonDown event-handler

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 .

在.NET 4.0中,您可以使用:

Keyboard.Modifiers.HasFlag(ModifierKeys.Control)

As Grzegorz Godlewski said above ( https://stackoverflow.com/a/34198469/3856798 ), Keyboard.Modifiers.HasFlag(ModifierKey.Control) can be used, and 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 https://stackoverflow.com/a/11665571 ).

But still nothing as fast as doing a native check (ie flagsToCheck & flag:= 0 ) judging by the conclusion here: https://stackoverflow.com/a/71038210

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM