我把这个MenuStrip
左停靠在一个表单中,带有LayoutStyle = VerticalStackWithOverflow
,我编写了这两个事件处理程序,使其项目仅在用户将鼠标移到 MenuStrip 上时才显示其文本:
Private Sub MenuStripMainMenu_MouseEnter(sender As Object, e As EventArgs) Handles MenuStripMainMenu.MouseEnter
For Each c In MenuStripMainMenu.Items.OfType(Of ToolStripItem)
c.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText
Next
End Sub
Private Sub MenuStripMainMenu_MouseLeave(sender As Object, e As EventArgs) Handles MenuStripMainMenu.MouseLeave, MenuStripMainMenu.LostFocus
For Each c In MenuStripMainMenu.Items.OfType(Of ToolStripItem)
c.DisplayStyle = ToolStripItemDisplayStyle.Image
Next
End Sub
虽然这工作正常,但某些菜单项有自己的菜单项(作为选择树),当用户将鼠标从根菜单条移动到选项时,菜单条收缩回其"仅图标"模式,因此展开的菜单看起来很笨拙。
有没有办法检测 MenuStrip 何时将其其中一个项目扩展为其子项目,以便我可以挂起正确的调整例程?
谢谢!
编辑
这是DonBoitnott移植到 VB.NET 的答案,我只在处理程序中添加了一个后续MenuDeactivate
,以便在菜单停用后立即将条带缩小回仅图像:
Private MenuStripMainMenu_activated As Boolean = False
Private Sub MenuStripMainMenu_MenuActivate(sender As Object, e As EventArgs) Handles MenuStripMainMenu.MenuActivate
MenuStripMainMenu_activated = True
End Sub
Private Sub MenuStripMainMenu_MenuDeactivate(sender As Object, e As EventArgs) Handles MenuStripMainMenu.MenuDeactivate
MenuStripMainMenu_activated = False
MenuStripMainMenu_MouseLeave(sender, e)
End Sub
Private Sub MenuStripMainMenu_MouseEnter(sender As Object, e As EventArgs) Handles MenuStripMainMenu.MouseEnter
For Each c In MenuStripMainMenu.Items.OfType(Of ToolStripItem)
c.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText
Next
End Sub
Private Sub MenuStripMainMenu_MouseLeave(sender As Object, e As EventArgs) Handles MenuStripMainMenu.MouseLeave
If Not MenuStripMainMenu_activated Then
For Each c In MenuStripMainMenu.Items.OfType(Of ToolStripItem)
c.DisplayStyle = ToolStripItemDisplayStyle.Image
Next
End If
End Sub
您当前拥有的事件的组合,以及添加MenuActivate
和MenuDeactivate
可以使其行为:
public partial class Form1 : Form
{
private Boolean _activated = false;
public Form1()
{
InitializeComponent();
}
private void menuStrip1_MouseEnter(Object sender, EventArgs e)
{
foreach (var c in menuStrip1.Items.OfType<ToolStripItem>())
c.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
}
private void menuStrip1_MouseLeave(Object sender, EventArgs e)
{
if (!_activated)
{
foreach (var c in menuStrip1.Items.OfType<ToolStripItem>())
c.DisplayStyle = ToolStripItemDisplayStyle.Image;
}
}
private void menuStrip1_MenuActivate(Object sender, EventArgs e)
{
_activated = true;
}
private void menuStrip1_MenuDeactivate(Object sender, EventArgs e)
{
_activated = false;
foreach (var c in menuStrip1.Items.OfType<ToolStripItem>())
c.DisplayStyle = ToolStripItemDisplayStyle.Image;
}
}