tags:

views:

398

answers:

3

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.

+2  A: 

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...

tommieb75
I accidentally used e.Modifiers in my example code instead of Keyboard.Modifiers, which is what I am actually using in my application. I apologize. I have not been able to get your example working with Keyboard.Modifiers.
Justin
i can't actually get that to work?
Paul Kohler
+3  A: 

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 :-)

Paul Kohler
I've read a little about KeyBinding, but why is it that they are better than using keyevents?
Justin
The whole solution is to use in conjunction with ApplicationCommands etc. It's just a neater pattern. Also you can abstract commands etc. There is a little bit to it but I don't think you'll actually get the original way to work because of how the events fire.
Paul Kohler
See http://msdn.microsoft.com/en-us/library/ms752308.aspx for official info. Also take a look at http://en.csharp-online.net/WPF_Concepts%E2%80%94Controls_with_Built-In_Command_Bindings - it may help with the "why?" :-)
Paul Kohler
Thanks for your help! And enduring my written question. It's greatly appreciated.
Justin
No worries! PK :-)
Paul Kohler
A: 

MSDN gives us this example:

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

does this work for you?

henchman
As said by Paul Kohler: "WPF 3.5 KeyEventArgs has no Modifiers property" I mistakenly used e.Modifiers in my example code. I apologize for the confusion.
Justin
I think a few of us were thrown by that! I thought it was a WinForms question at first :)
Paul Kohler
ditto :-) *memo to myself: read tags*
henchman