WPF: When Alt key is pressed, my ContextMenu won't open

淺唱寂寞╮ 提交于 2019-12-24 06:28:11

问题


In my WPF app, when a ContextMenu is opening, I want to tweak its menu items depending on whether or not the Alt key is pressed.

I've got the logic working. XAML:

<my:Control ContextMenuOpening="MyContextMenu_Opening" />

Code:

private void MyContextMenu_Opening(object sender, RoutedEventArgs args) {
  bool isAltDown = Keyboard.IsKeyDown(Key.LeftAlt);
  /* tweak menu items here */
}

My problem is that when the Alt key is pressed, the context menu opens and then immediately closes (I can see in the flash of it being open that my logic is at least working).

I wonder is this a WPF 'feature' in general because if I even hold Alt while right clicking on a TextField, the same thing happens - the built-in Cut/Copy/Paste menu flashes open then immediately closes.

One hunch is that it has something to do with Alt activating the application menu bar. But an application menu bar does not apply to my situation, so if the solution involves messing with that, it will still work for me.


回答1:


This is a built-In behavior in the MenuBase class:

        protected override void OnKeyDown(KeyEventArgs e)
        {
            .....
            if (((e.SystemKey == Key.LeftAlt) || (e.SystemKey == Key.RightAlt)) || (e.SystemKey == Key.F10))
            {
                this.KeyboardLeaveMenuMode();
                e.Handled = true;
            }
        }

Why not use another Modifier Key ??




回答2:


this is a built in behavior from MSDN MenuBase.OnKeyDown

    If the user presses ESC, ALT+ALT, or ALT+F10, 
    this implementation marks the KeyDown event as handled 
    by setting the Handled property of the event data to true.



回答3:


You can still use the Alt key, just override the base class behavior:

public class AltProofContextMenu : ContextMenu
{
    protected override void OnKeyDown(KeyEventArgs e)
    {
        if(!(e.SystemKey == Key.LeftAlt || e.SystemKey == Key.RightAlt))
            base.OnKeyDown(e);
    }
}


来源:https://stackoverflow.com/questions/15246865/wpf-when-alt-key-is-pressed-my-contextmenu-wont-open

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