问题
Today I got some new restrictions on my WPF user interface that should eliminate the permanent visibility of the MenuBar.
I thought of imitating the user interface of Windows Live Messenger. That application displays the MenuBar only if the ALT-key is pressed. And hides it again when the focus on the MenuBar is lost.
Currently I don't have a clue how to build such a thing in WPF... is something like this possible?
Thanks in advance.
回答1:
You can write a key down event on main window..
KeyDown="Window_KeyDown"
and in the code behind file..
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.LeftAlt || e.Key == Key.RightAlt)
{
myMenu.Visibility = Visibility.Visible;
}
}
if you want to achive this with MVVM or using bindings... you can use input key bindings
<Window.InputBindings>
<KeyBinding Key="LeftAlt" Command="{Binding ShowMenuCommand}"/>
<KeyBinding Key="RightAlt" Command="{Binding ShowMenuCommand}"/>
</Window.InputBindings>
回答2:
I think that the correct implementation is with KeyUp. This is the behaviour of IE8, Vista, Windows7 and other recent MS products:
private void MainWindow_KeyUp(Object sender, KeyEventArgs e)
{
if (e.Key == Key.System)
{
if (mainMenu.Visibility == Visibility.Collapsed)
mainMenu.Visibility = Visibility.Visible;
else
mainMenu.Visibility = Visibility.Collapsed;
}
}
回答3:
This is what I understood:
private void form_KeyDown(object sender,
System.Windows.Forms.KeyEventArgs e)
{
if(e.KeyCode == Keys.Alt && /*menu is not displayed*/)
{
// display menu
}
}
private void form_KeyUp(object sender,
System.Windows.Forms.MouseEventArgs e)
{
if (/*check if mouse is NOT over menu using e.X and e.Y*/)
{
// hide menu
}
}
If you need something different play a little with keyboard and mouse events.
回答4:
You can use the KeyDown (or Preview version if you prefer) and then check for the System key like this:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.KeyDown += new KeyEventHandler(MainWindow_KeyDown);
}
void MainWindow_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.System && (Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt)
{
// ALT key pressed!
}
}
}
来源:https://stackoverflow.com/questions/6679197/how-to-make-wpf-menubar-visibile-when-alt-key-is-pressed