views:

388

answers:

3

I have a custom control (C#, visual studio). I want to show a tooltip on the mousehover event.

However, no matter what I do, it either never shows or has a chance of showing multiple times.

I thought it would be as simple as:

private void MyControl_MouseHover(object sender, EventArgs e)
{
    ToolTip tT = new ToolTip();

    tT.Show("Why So Many Times?", this);
}

But this does not work. I have tried a bunch of things but cannot seem to get it to work. I would like to have the tooltip be part of the component because I want to access private fields from it for display.

Thanks for any help

A: 

Have you tried instantiating the tooltip in your constructor and showing it on the mouse hover?

public ToolTip tT { get; set; }

public ClassConstructor()
{
    tT = new ToolTip();
}

private void MyControl_MouseHover(object sender, EventArgs e)
{
    tT.Show("Why So Many Times?", this);
}
Joseph
This works.However, I tried:private ToolTip tT = new ToolTip();outside of the mousehover event and that didn't work either.Why is it different instantiating in the constructor rather than when it is declared?
EatATaco
Actually, I just tried doing it that way again and it worked. Not sure what I screwed up the first time. Thanks again.
EatATaco
@EatATaco glad I could help!
Joseph
A: 

The MouseHover is fired every time the mouse moves over your control. So your are creating a new tooltip every single time the event is fired. That's why you see multiple instances of this widget. Try the Joseph's answer

Mario
+1  A: 

Just adding a tooltip using the designer generates wildly different code than that in the question.

Form1.Designer.cs: (private variables moved to the top of the class for readability)

partial class Form1
{
    private System.ComponentModel.IContainer components = null;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.ToolTip toolTip1;

    // ...

    private void InitializeComponent()
    {
        this.components = new System.ComponentModel.Container();
        this.label1 = new System.Windows.Forms.Label();
        this.toolTip1 = new System.Windows.Forms.Tooltip(this.components);

        // ...

        this.toolTip1.SetToolTip(this.label1, "abc");

        // ...
    }
}

I'm sure you could extract just the tooltip and container stuff into your component.

Jon Seigel
Thanks for this answer.
Heath Hunnicutt