WPF Keyboard Shortcut - Why Doesn't It Work?

I have the following code (which does not work):

private void Window_PreviewKeyDown(object sender, KeyEventArgs e) {
    e.Handled = true;
    if ((e.Key == Key.P) && (Keyboard.Modifiers == ModifierKeys.Alt)) {
        MessageBox.Show("Thanks!");
    }            
}

Why is this not working? The event fires, but

(e.Key == Key.P) && (Keyboard.Modifiers == ModifierKeys.Alt))

never evaluates to true. My similar events using Ctrlinstead Altwork in this way. My events also work, which include Ctrl and Alt .

+5
source share
3 answers

The best way to work with keys in WPF is Basic gestures

eg. note that this is an example, not a solution

<Window.InputBindings>
  <KeyBinding Command="ApplicationCommands.Open" Gesture="ALT+P" />
</Window.InputBindings>

There you have most of this, but you will work quite easily. This is a WPF way to handle keys!

PK :-)

+3
source

"" ModifierKeys, ...

    private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if ((e.Key == Key.P) && ((e.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt))
        {
            MessageBox.Show("Thanks!");
            e.Handled = true;
        }
    }

, Handled e...

+2

MSDN gives us the following example:

if(e.Key == Key.P && e.Modifiers == Keys.Alt)

Does this work for you?

0
source

All Articles