本文介绍了Autohide MenuStrip-如何在显示时激活它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MenuStrip,并使用以下代码将其设置为AutoHide.它隐藏/显示完美状态,但是当控件获得焦点时,通过按键,会显示MenuStrip,但它不处于活动状态,并且快捷键下没有小的下划线,例如File的"F"下,然后按'F'不会将其打开).如何正确激活它?

I have a MenuStrip and I make it AutoHide using following code. It hides/shows prefect but when a control get focus, by pressing key, MenuStrip shows but it is not active and there is not small underline under shortcut keys for example under 'F' for File , and pressing 'F' will not open it). How can I correctly active it?

注意:我使用MenuDeactivate代替它,但是它不起作用.

Note: I used MenuDeactivate instead of it but it did not work prefect.

bool menuBarIsHide = true;
bool altKeyIsDown = false;
bool alwaysShowMenuBar=false;
//KeyPreview is true;
//for prevent glitch(open/close rapidly)
void Form1_KeyUp(object sender, KeyEventArgs e)
{
    if ((Control.ModifierKeys & Keys.Alt) != 0)
        altKeyIsDown = false;
}
void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if ((Control.ModifierKeys & Keys.Alt) != 0)
    {
        if (altKeyIsDown)
            return;
        if (!alwaysShowMenuBar)
        {
            if (menuBarIsHide)
            {
                menuBar.Show();
                menuBarIsHide = false;
                //manage container height
            }
            else
            {
                menuBar.Hide();
                menuBarIsHide = true;
                //manage container height
            }
        }
    }
}

推荐答案

您可以覆盖 ProcessCmdKey 处理键可切换菜单可见性.同样要激活菜单,请调用MenuStrip的内部OnMenuKey方法.还要处理 MenuDeactivate 使菜单工作完成后使菜单不可见,但是您需要使用 BeginInvoke .

You can override ProcessCmdKey to handle key to toggle the menu visibility. Also to activate menu, call internal OnMenuKey method of MenuStrip. Also handle MenuDeactivate to make the menu invisible after finishing your work with menu, but you need to make the menu invisible using BeginInvoke.

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == (Keys.Alt | Keys.Menu))
    {
        if (!this.menuStrip1.Visible)
        {
            this.menuStrip1.Visible = true;
            var OnMenuKey = menuStrip1.GetType().GetMethod("OnMenuKey", 
                System.Reflection.BindingFlags.NonPublic | 
                System.Reflection.BindingFlags.Instance);
            OnMenuKey.Invoke(this.menuStrip1, null);
        }
        else
        {
            this.menuStrip1.Visible = false;
        }
        return true;
    }
    return base.ProcessCmdKey(ref msg, keyData);
}
private void menuStrip1_MenuDeactivate(object sender, EventArgs e)
{
    this.BeginInvoke(new Action(() => { this.menuStrip1.Visible = false; }));
}

这篇关于Autohide MenuStrip-如何在显示时激活它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 20:20