0
votes

I am working on an exercise to create a custom control. The custom control is a simple label inheriting Control.

Using the tool tip code below:

m_toolTip = new ToolTip();

protected override void OnMouseMove(MouseEventArgs e) {
    m_toolTip.SetToolTip(this, Text);
    base.OnMouseMove(e);
}

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

No configurations are used for the tool tip.

When I mouse over the label (although you can't see the mouse): enter image description here

Now, after I have left the control and moused over the second label: enter image description here

When you hover the mouse over a MS Label, the tool tip will show up and then immediately disappears. How can I better duplicate the behavior that the standard MS label displays?

3

3 Answers

0
votes

I would use the MouseEnter event instead of MouseMove. You could use a Timer so that it would not display immediately, but rather after a short period of time.

For example:

// Member Variables
ToolTip toolTip = new ToolTip();
string toolTipText = "Your tool tip goes here.";
Timer toolTipTimer = new Timer();

public TimeSpan ToolTipDelay
{
  get { return TimeSpan.FromMilliseconds(toolTipTimer.Interval); }
  set { toolTipTimer.Interval = (int)value.TotalMilliseconds; }
}

// Call this in your CustomControl constructor!
void InitializeToolTipTimer()
{
  this.ToolTipDelay = TimeSpan.FromSeconds(1);

  toolTipTimer.Tick += (sender, e) =>
  {
    toolTipTimer.Stop(); // Tick only once per MouseEnter
    toolTip.SetToolTip(this, toolTipText);
  };
}

void OnToolTipMouseEnter(object sender, EventArgs e)
{
  toolTipTimer.Start(); // Start the ToolTip display Timer
}

void OnToolTipMouseLeave(object sender, EventArgs e)
{
  toolTipTimer.Stop(); // Cancel any pending ToolTip display
  toolTip.RemoveAll();      
}
0
votes

I resolved the issue with the following change:

protected override void OnMouseHover(EventArgs e) {
    var m_position = PointToClient(Control.MousePosition);
    m_toolTip.Show(Text, this, m_position.X + 10, m_position.Y, 20000);
    base.OnMouseHover(e);
}

I removed the previous OnMouseMove override.

Additionally, I also tweaked some settings that seem to work for me.

0
votes

You don't need to set the tooltip every time you want to display it.

You should set it up in the control constructor:

m_toolTip.SetToolTip(this, Text);

and then the showing and hiding of the tooltip is done automatically for you without you having to write any extra code.