Willy
Willy

Reputation: 10660

C# WinForms: How to know/detect if tooltip is being displayed/shown

I have created a tooltip. This tooltip is shown when mouse is over an icon by calling the show method of the tooltip. I want to know if this tooltip is currently being displayed. How to do this? Maybe through reflection?

System.Reflection.FieldInfo fi = typeof(ToolTip).GetField("window", BindingFlags.NonPublic | BindingFlags.Instance);
fi.GetValue(someObject...) ...

and then request maybe if visible?

Upvotes: 4

Views: 2705

Answers (1)

KeithS
KeithS

Reputation: 71601

The ToolTip class raises its Popup event just before it begins to display the tooltip. You can consider this the start of the time span during which the TT is displayed. The end of that span is the first of two things; a MouseLeave event on the control for which the ToolTip was showing, indicating the user is no longer pointing the mouse at whatever you had been showing a ToolTip for, or the passage of the AutoPopDelay time period of the ToolTip after which the balloon will fade out.

So, you can handle this with code in your Form or other control containing the ToolTip, looking something like this:

private System.Windows.Forms.Timer ToolTipTimer = new Timer();

public MyControl()
{
    myToolTip.Popup += ToolTipPopup;
    ToolTipTimer.Tick += ToolTipTimerTick;
    ToolTipTimer.Enabled = false;
}

private bool IsToolTipShowing { get; set; }

private Control ToolTipControl { get; set; }

private void ToolTipPopup(object sender, PopupEventArgs e)
{
   var control = e.AssociatedControl;

   //optionally check to see if we're interested in watching this control's ToolTip    

   ToolTipControl = control;
   ToolTipControl.MouseLeave += ToolTipMouseLeave;
   ToolTipAutoPopTimer.Interval = myToolTip.AutoPopDelay;
   ToolTipTimer.Start(); 
   IsToolTipShowing = true;
}

//now one of these two should happen to stop the ToolTip showing on the currently-watched control
public void ToolTipTimerTick(object sender, EventArgs e)
{
   StopToolTip();
}

public void ToolTipMouseLeave(object sender, EventArgs e)
{
   StopTimer();
}

private void StopTimer()
{
   IsToolTipShowing = false;
   ToolTipTimer.Stop();
   ToolTipControl.MouseLeave -= ToolTipMouseLeave;
}

Upvotes: 3

Related Questions