Autohide MenuStrip-如何在显示时激活它? [英] Autohide MenuStrip - How to activate it when showing?

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

问题描述

我有一个MenuStrip,并使用以下代码将其设置为AutoHide.它隐藏/显示完美状态,但是当控件获得焦点时,通过按 Alt 键,会显示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 Alt 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
            }
        }
    }
}

推荐答案

您可以覆盖 BeginInvoke .

You can override 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; }));
}

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆