Question

Hey all, I am not sure if this is possible, but I am trying to dynamically add a tooltip to an image using the Graphics method - DrawImage. I dont see any properties or events for when the image is moused over or anything so I don't know where to begin. I am using WinForms (in C# - .NET 3.5). Any ideas or suggestions would be appreciated. Thanks.

Was it helpful?

Solution

I would guess that you have some sort of UserControl and you call DrawImage() in the OnPaint method.

Given that, your tooltip will have to controlled explicitly. Basically, create a Tooltip on your Form, give that to your control via a property, show the tooltip when your control received a MouseHover event and hide the tooltip when you receive a MouseLeave event.

Something like this:

public partial class UserControl1 : UserControl
{
    public UserControl1() {
        InitializeComponent();
    }

    protected override void OnPaint(PaintEventArgs e) {
        base.OnPaint(e);

        // draw image here
    }

    public ToolTip ToolTip { get; set; }

    protected override void OnMouseLeave(EventArgs e) {
        base.OnMouseLeave(e);

        if (this.ToolTip != null)
            this.ToolTip.Hide(this);
    }

    protected override void OnMouseHover(EventArgs e) {
        base.OnMouseHover(e);

        if (this.ToolTip == null)
            return;

        Point pt = this.PointToClient(Cursor.Position);
        String msg = this.CalculateMsgAt(pt);
        if (String.IsNullOrEmpty(msg))
            return;

        pt.Y += 20;
        this.ToolTip.Show(msg, this, pt);
    }

    private string CalculateMsgAt(Point pt) {
        // Calculate the message that should be shown 
        // when the mouse is at thegiven point
        return "This is a tooltip";
    }
}

OTHER TIPS

Remember, you have to store bounds of the Image that you are drawing and in the mouseMove event check if the location of current Mouse cursor at that region, then display ToolTip else hide it.

    ToolTip t; 
    private void Form1_Load(object sender, EventArgs e)
    {
         t = new ToolTip();  //tooltip to control on which you are drawing your Image
    }

    Rectangle rect; //to store the bounds of your Image
    private void Panel1_Paint(object sender, PaintEventArgs e)
    {
        rect =new Rectangle(50,50,200,200); // setting bounds to rect to draw image
        e.Graphics.DrawImage(yourImage,rect); //draw your Image
    }

    private void Panel1_MouseMove(object sender, MouseEventArgs e)
    {

        if (rect.Contains(e.Location)) //checking cursor Location if inside the rect
        {
            t.SetToolTip(Panel1, "Hello");//setting tooltip to Panel1
        }
        else
        {
            t.Hide(Panel1); //hiding tooltip if the cursor outside the rect
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top