自动隐藏 MenuStrip - 如何在显示时激活它?

Autohide MenuStrip - How to activate it when showing?

我有一个 MenuStrip,我使用以下代码将其设为 AutoHide。它 hides/shows 完美但是当控件获得焦点时,通过按 Alt 键, MenuStrip 显示但它不是活动的并且快捷键下没有小下划线例如在 'F' 下的 File ,按 'F' 将不会打开它)。我怎样才能正确激活它?

注意:我用 MenuDeactivate 代替它,但效果不佳。

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 to handle Alt 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; }));
}