How to make WPF MenuBar visibile when ALT-key is pressed?

允我心安 提交于 2019-12-07 15:16:37

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>

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

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.

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!
        }
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!