我设计了以下代码,用于在鼠标悬停时显示控件的 Tag 属性。该代码适用于标签和文本框等标准控件,但我无法让它适用于我的 MenuItems(更具体地说是 ToolStripMenuItems)。大家可以看看我的代码并告诉我我做错了什么吗?提前致谢!
public void Form1_Load(object sender, EventArgs e)
{
...
this.addEventsToAllComponents(this);
}
private void addEventsToAllComponents(Component component)
{
if (component is MenuItem)
{
MenuItem menuItem = component as MenuItem;
menuItem.Select += new EventHandler(menuItem_Select);
}
else if (component is Control)
{
Control ctrl = component as Control;
foreach (Control control in ctrl.Controls)
{
control.MouseEnter += new EventHandler(this.control_MouseEnter);
control.MouseLeave += new EventHandler(this.control_MouseLeave);
if (control.HasChildren)
addEventsToAllComponents(control);
}
}
}
private void menuItem_Select(object sender, EventArgs e)
{
MenuItem menuItem = sender as MenuItem;
if (menuItem.Tag.ToString().Length > 0)
this.toolStripStatusLabel1.Text = menuItem.Tag.ToString();
}
private void control_MouseEnter(object sender, EventArgs e)
{
Control control = sender as Control;
if (control.Tag.ToString().Length > 0)
this.toolStripStatusLabel1.Text = control.Tag.ToString();
}
private void control_MouseLeave(object sender, EventArgs e)
{
if (this.toolStripStatusLabel1.Text.ToString().Length > 0)
this.toolStripStatusLabel1.Text = "";
}