Justin
Justin

Reputation: 2479

WPF Keyboard Shortcut - Why is this not working?

I have the follwing code (which is not working):

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

Why doesn't this work? The event is firing, but

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

never evaluates to true. My similar events using Ctrl instead of Alt in this way work. Also my events that include Ctrl and Alt work as well.

Upvotes: 5

Views: 5521

Answers (3)

Paul Kohler
Paul Kohler

Reputation: 2714

A better way to work with keys in WPF is Key Gestures

e.g. note that this is an example, not a solution

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

There's more to it that that but you'll work it easily enough. That's the WPF way to handle keys!

PK :-)

Upvotes: 3

Phil Rykoff
Phil Rykoff

Reputation: 12087

MSDN gives us this example:

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

does this work for you?

Upvotes: 0

t0mm13b
t0mm13b

Reputation: 34592

You need to do a 'bitwise and' with the ModifierKeys as shown below...

    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;
        }
    }

Also, do not forget to set the Handled property of the e parameter...

Upvotes: 2

Related Questions