NumericUpDown is not changing ToolStripStatusLabel when MouseEnter

503 Views Asked by At

I used this code to implement on hover tooltip, it works with TextBox, ComboBox, MaskedTextBox but not on NumericUpDown. Does anybody know why it is not working?

public static void addHovertip(ToolStripStatusLabel lb, Control c, string tip)
        {

            c.MouseEnter += (sender, e) =>
            {
                lb.Text = tip;
                // MessageBox.Show(c.Name);
            };
            c.MouseLeave += (sender, e) =>
            {
                lb.Text = "";

            };
        }
1

There are 1 best solutions below

0
On BEST ANSWER

I admit the deleted answer from Hans Passant helped a bit in creating this answer.

First of all your code works fine. If you're working with events that happen rather often (like the MouseEvents) you better add a Debug.WriteLine to your code so you can see in the Debugger Output Window which events, for which controls, in which order take place.

The main problem is that due to the fact that the numeric up/down control is a control that is buildup with two different child controls your MouseLeave event is called as soon as the mouse enters one of the two child controls. What happens is: MouseEnter is called when the mouse hits the single line border of the control and MouseLeave is called the moment the mouse is no longer on that line. In MouseLeave you set the Label to an emtpy string. That gives the impression that your code doesn't work.

By simply adding a loop to go over any child controls solves this issue. This still set the label to an empty string a bit to often but it is also immediately set to the correct text if needed.

Here is the changed code with the Debug statements in place.

    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);
        }
    }

For completeness here is the Load event of my test form:

 private void Form1_Load(object sender, EventArgs e)
 {
     addHovertip((ToolStripStatusLabel) statusStrip1.Items[0], this.numericUpDown1, "fubar");
 }

Here is an animated gif demonstrating what happens when you move the mouse in and out the Numeric Up Down control:

numeric up down control and mouse event debug output