c# - 自动隐藏菜单条

标签 c# .net winforms

我正在开发一个 Windows 窗体项目,最近我添加了代码以默认隐藏 MenuStrip,除非用户按下 Alt 键,以与最新版本的 Windows 视觉实践保持一致。

我想要做的是通过启用 MenuStrip 在特定时间范围内未检测到事件时自动隐藏来完成此添加。言归正传,这是我迄今为止起草的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SomeWinformProject {
    public partial class MainForm : Form {
        /* Construction */
        public MainForm () {
            InitializeComponent ();
            this.KeyDown += new KeyEventHandler(this.MainForm_KeyDown);
            this.KeyPreview = true;
            this.menuStrip.Visible = false;
        }

        /* Alt key event handler */
        private void MainForm_KeyDown (object sender, KeyEventArgs e) {
            /* if the Alt key is pressed and the menuStrip is not currently
             * visible, un-hide it */
             if (e.Alt && !(this.menuStrip.Visible))
                 this.menuStrip.Visible = true;
        }
    }
}

以下是我自己解决此问题的想法:

  1. 创建一个名为 menuStripActivity 效果的公共(public) bool 值,并在 MainForm_KeyDown() 中将其设置为 false。然后,我考虑以 5 秒左右的间隔创建一个计时器实例,并将 MouseClick 事件附加到 menuStrip。如果发生 MouseClick 事件,则 menuStripActivity 将设置为 true,并且计时器中断将选择不执行任何操作,而不是隐藏 MenuStrip。
  2. 我意识到上述内容存在的问题是,它没有考虑到用户正在做某事或导航menuStrip的可能性选项。我在 MSDN 文档中读到,还存在一个 MouseHover 事件处理程序,在这种情况下,当计时器发生故障时,我可以对两个处理程序的结果进行“或”操作。

这两个问题的问题是,我对 C# 和整个 .NET 生态系统相当陌生,所以我不太清楚什么是正确的,什么是错误的。我想避免我的代码从一开始就困惑,并希望在这种情况下选择“最佳实践”。

任何人都可以帮助我指出正确的方向(或告诉我我正在犯的错误)吗?

最佳答案

您可以收听MenuStrip.MenuDeactivate事件:

public MainForm () {
    InitializeComponent ();

    this.KeyPreview = true;
    this.KeyDown += new KeyEventHandler(this.MainForm_KeyDown);
    this.menuStrip.MenuDeactivate += (s, e) => this.menuStrip.Visible = false;

    this.menuStrip.Visible = false;
}

Remarks
When activated by the ALT key, the MenuStrip or ToolStrip typically neither take nor remove the focus from the control that currently has the focus. If there is a control hosted within the MenuStrip or a drop-down of the MenuStrip, the control gains focus when the user presses the TAB key. In general, the GotFocus, LostFocus, Enter, and Leave events of MenuStrip might not be raised when they are activated by the keyboard. In such cases, use the MenuActivate and MenuDeactivate events instead.

关于c# - 自动隐藏菜单条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37579022/

相关文章:

c# - 接口(interface)继承和抽象方法覆盖

c# - yield 返回 vs Lazy<T>

c# - 来电显示检测 : Doesnt work with some phones

c# - 缩放 WinForms TableLayoutPanel

.net - 如何在数据绑定(bind)场景(即 BindingList)中验证自定义对象的属性?

c# - 格式化一个大的 double 以显示四位有效数字

c# - 如何在 C# 中使用 List<int> 作为 SQL 参数

.net - 有没有办法防止 Azure 限制我的 csv 读取速度?

c# - ADO.Net SQLCommand.ExecuteReader() 变慢或挂起

.net - 如何取消单选按钮或复选框选中的更改