4

I'm new to WPF and in an application i'm building I'd like to show the main menu when the alt key is pressed just like windows explorer in vista and windows 7. I've tried using a keybinding with just the modifier set but that doesn't seem to work.

Heres by code so far:

<Window.CommandBindings>
    <CommandBinding Command="{x:Static local:MainWindow.ShowMenuCommand}"
                        CanExecute="ShowMenuCommand_CanExecute"
                        Executed="ShowMenuCommand_Executed"/>
</Window.CommandBindings>
<Window.InputBindings>
    <KeyBinding Key="Alt" Command="{x:Static local:MainWindow.ShowMenuCommand}" />
</Window.InputBindings>

I'd also like the menu to disappear when the focus is lost.

Any ideas?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
jamier
  • 802
  • 1
  • 8
  • 9

5 Answers5

2

Disclaimer: This is not an attempt at an answer as the user has already found a solution. This is just to provide additional information on the subject.

For anyone that wants to know why @jamier's attempt at this KeyBinding doesn't work, the answer can be found in the KeyBinding Class page on MSDN:

With the exception of the function keys and the numeric keypad keys, a valid KeyGesture must contain exactly one Key and one or more ModifierKeys.

Therefore, one modifier on its own cannot be used as a valid Gesture in a KeyBinding.

Sheridan
  • 68,826
  • 24
  • 143
  • 183
2

The answer I was looking for can be found here:

http://www.stackoverflow.com/questions/1218394/how-can-i-toggle-the-main-menu-visibility-using-the-alt-key-in-wpf

Thanks to everyone for the help.

jamier
  • 802
  • 1
  • 8
  • 9
1

Have you tried setting the Key attribute to "LeftAlt" or "RightAlt"? The Key attribute is of type System.Windows.Input.Key enumeration, which doesn't have an "Alt" value.

Alt is used as a modifier in a KeyGesture, so that is why you see it separately in other places. However, in the Key enumeration, it specifically has instances for the left and right Alt keys.

You will more than likely have to have two bindings, one for each alt key.

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
casperOne
  • 73,706
  • 19
  • 184
  • 253
0

Try to set Modifiers="Alt" and Key="LeftAlt":

<KeyBinding Key="LeftAlt" Modifiers="Alt" Command="{x:Static local:MainWindow.ShowMenuCommand}" /> 
Marcus L
  • 4,030
  • 6
  • 34
  • 42
  • Setting this from code gives a `System.NotSupportedException` with message `'Alt+LeftAlt' key and modifier combination is not supported for KeyGesture.` in .NET Framework 4 – cod3monk3y Nov 05 '13 at 16:07
0

Try setting IsMainMenu="True" on your Menu control. Does that give you the behavior you're looking for?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
John Bowen
  • 24,213
  • 4
  • 58
  • 56