我承认 Hans Passant 删除的答案有助于创建这个答案。
首先,您的代码工作正常。如果您正在处理经常发生的事件(例如 MouseEvents),您最好将 a 添加Debug.WriteLine
到您的代码中,这样您就可以在调试器输出窗口中查看哪些事件、哪些控件以及发生的顺序。
主要问题是,由于数字向上/向下控件是一个由两个不同子控件组成的控件,因此只要鼠标进入两个子控件之一,就会调用 MouseLeave 事件。发生的情况是:当鼠标碰到控件的单行边框时调用 MouseEnter,当鼠标不再在该行上时调用 MouseLeave。在 MouseLeave 中,您将 Label 设置为一个空字符串。这给人的印象是您的代码不起作用。
通过简单地添加一个循环来遍历任何子控件即可解决此问题。这仍然会经常将标签设置为空字符串,但如果需要,它也会立即设置为正确的文本。
这是带有 Debug 语句的更改代码。
public static void addHovertip(ToolStripStatusLabel lb, Control c, string tip)
{
c.MouseEnter += (sender, e) =>
{
Debug.WriteLine(String.Format("enter {0}", c));
lb.Text = tip;
};
c.MouseLeave += (sender, e) =>
{
Debug.WriteLine(String.Format("Leave {0}", c));
lb.Text = "";
};
// iterate over any child controls
foreach(Control child in c.Controls)
{
// and add the hover tip on
// those childs as well
addHovertip(lb, child, tip);
}
}
为了完整起见,这里是我的测试表单的 Load 事件:
private void Form1_Load(object sender, EventArgs e)
{
addHovertip((ToolStripStatusLabel) statusStrip1.Items[0], this.numericUpDown1, "fubar");
}
这是一个动画 gif,演示了当您将鼠标移入和移出 Numeric Up Down 控件时会发生什么:
