[英]How do I hide a window form when x is clicked and CLose through system tray ToolStripMenuItem
[英]How do I close a toolstripmenuitem that is set to autoclose = false?
我有一个菜单项,用户可以切换。 我希望菜单保持打开状态,以便用户可以检查他们想要的所有项目。 我设置autoclose = false,现在效果很好。 但是,我现在也无法关闭窗口。 我尝试单击菜单上的窗体,单击转义,单击菜单项,单击菜单的组合键,但没有任何效果。
理想情况下,我希望用户能够单击表单或除菜单以外的几乎所有内容来关闭它或按Escape键。 我该怎么做? 我尝试在窗体上创建一个getfocus事件并在其中执行item.HideDropDown,但没有骰子。
谢谢!
生成表单的click事件,然后遍历每一个没有自己的click事件的控件,将其click事件设置为表单的click事件。
在这种情况下,请包含隐藏菜单的代码: toolStripDropDownButton.HideDropDown();
将代码复制到其他控件的任何现有单击事件。
当您单击表单上的任意位置时,这就是我如何隐藏月历的方式。
而且,如果您还希望包含按转义的选项,请对KeyDown事件执行相同的操作,并在运行代码之前检查它是否为转义键。
我有类似的问题,这是我的解决方案。 我创建了通用的MouseEnter和MouseLeave事件处理程序,并使用计时器在鼠标离开菜单后延迟关闭菜单。
以下是包含3个项目和1个分隔符的菜单的示例代码。 在示例中,有2个项目可使用“自动关闭”功能,而其中一个(_modeChangingItem)不会关闭菜单。 您可以轻松地根据自己的需要对此进行自定义,例如,不选择“自动关闭”。
private Timer _menuTimer = new Timer();
private void MainFrm_Load (object sender, EventArgs e)
{
_menuTimer.Interval = 200;
_menuTimer.Tick += _menuTimer_Tick;
_rootMenuItem.MouseEnter += commonMenu_MouseEnter;
_rootMenuItem.MouseLeave += commonMenu_MouseLeave;
_menuItem1.MouseEnter += commonMenu_MouseEnter;
_menuItem1.MouseLeave += commonMenu_MouseLeave;
_menuItem2.MouseEnter += commonMenu_MouseEnter;
_menuItem2.MouseLeave += commonMenu_MouseLeave;
_separator.MouseEnter += commonMenu_MouseEnter;
_separator.MouseLeave += commonMenu_MouseLeave;
_modeChangingItem.MouseEnter += commonMenu_MouseEnter;
_modeChangingItem.MouseLeave += commonMenu_MouseLeave;
}
private void commonMenu_MouseLeave(object sender, EventArgs e)
{
_menuTimer.Stop();
// Comment this line out if you want none of the items to AutoClose
_rootMenuItem.DropDown.AutoClose = true;
ToolStripMenuItem menuItem = sender as ToolStripMenuItem;
if (menuItem != null) menuItem.Tag = null;
ToolStripSeparator separator = sender as ToolStripSeparator;
if (separator != null) separator.Tag = null;
_menuTimer.Start();
}
private void commonMenu_MouseEnter(object sender, EventArgs e)
{
ToolStripMenuItem menuItem = sender as ToolStripMenuItem;
if (menuItem != null) menuItem.Tag = new object();
ToolStripSeparator separator = sender as ToolStripSeparator;
if (separator != null) separator.Tag = new object();
}
private void _menuTimer_Tick(object sender, EventArgs e)
{
if (_rootMenuItem.Tag == null && _menuItem1.Tag == null &&
_menuItem2.Tag == null &&
_separator.Tag == null &&
_modeChangingItem.Tag == null)
{
_rootMenuItem.DropDown.Close();
}
_menuTimer.Stop();
}
private void _modeChangingItem_Click(object sender, EventArgs e)
{
ToolStripMenuItem menuItem = sender as ToolStripMenuItem;
if (menuItem == null) return;
// Move this line to Form_Load if you want none of the items AutoClose
_rootMenuItem.DropDown.AutoClose = false; // Now the menu stays opened
[...]
}
该解决方案为用户节省了额外的点击时间-当您将鼠标移到所有项目之外时,计时器关闭菜单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.