Search code examples
c#winformstooltip

Setting x & y on ToolTip.Show somehow sets duration as well?


When I call ToolTip.Show() like below;

ToolTip.Show(Message, MyControl);

Everything works perfectly, it shows and goes away when MyControl looses focus. However the position of the ToolTip is over MyControl so I want to add an offset;

ToolTip.Show(Message,MyControl,10,-20);

The ToolTip does position the way I want, it shows when hovering over, but is does not disappear anymore on MyControl loosing focus. The behaviour is similar to setting the duration very high.

When I look at the ToolTip.Show() definition, one of the ways to call it is like this;

public void Show(string text, IWin32Window window, int x, int y);

So how can the ToolTip suddenly stop disappearing when I only add the x & y offset and not touch the duration?

Below the full code:

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WFA
{
  public class Form1 : Form
  {
    public Form1()
    {
        UC UC = new UC();
        this.Controls.Add(UC);
    }
  }

  public class UC : UserControl
  {
    String Message = "Hello!";
    PictureBox MyControl = new PictureBox();
    ToolTip ToolTip = new ToolTip();

    public UC()
    {
        MyControl.ImageLocation = "https://i.sstatic.net/CR5ih.png";
        MyControl.Location = new Point(100, 100);
        this.Controls.Add(MyControl);
        MyControl.MouseHover += ShowToolTip;
    }

    private void ShowToolTip(object sender, EventArgs e)
    {
        ToolTip.Show(Message, MyControl,10,-20); // this will never disappear??
      //ToolTip.Show(Message, MyControl); // this disappears after leaving
    }
  }
}

Solution

  • By default, if you don't specify any "Timeout", ToolTip will be hidden only when the parent form is deactivated.

    If you want to hide the tooltip when mouse leaves your control you've to manually do it by calling ToolTip.Hide.

    public UC()
    {
        BorderStyle = BorderStyle.FixedSingle;
        MyControl.ImageLocation = "https://i.sstatic.net/CR5ih.png";
        MyControl.Location = new Point(100, 100);
        this.Controls.Add(MyControl);
        MyControl.MouseHover += ShowToolTip;
    
        //Subscribe MouseLeave and hide the tooltip there
        MyControl.MouseLeave += MyControl_MouseLeave;
    }
    
    void MyControl_MouseLeave(object sender, EventArgs e)
    {
        ToolTip.Hide(MyControl);
    }