ToolTip for custom control

C

cronusf

I have a custom control that draws some of its elements. When the
mouse is over certain areas, I want to display a tooltip. The problem
is that these elements are not Controls, so I cannot use
ToolTip.SetToolTip.

Is there an API so that I can draw a tooltip with the text and
position I want?
 
J

Jeremy Shovan

This might do the trick for you. Below is some code for a user control that
does just what you want it to do..


public partial class UserControl1 : UserControl
{
private readonly ToolTip tTip = new ToolTip();
private readonly List<TipRegion> tipRegionCollection = new
List<TipRegion>();
public UserControl1()
{
InitializeComponent();
tipRegionCollection.Add(new TipRegion(new Rectangle(new Point(10, 10),
new Size(50, 50)), "Region 1"));
tipRegionCollection.Add(new TipRegion(new Rectangle(new Point(70, 10),
new Size(100, 100)), "Region 2"));
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics graphics = e.Graphics;
foreach(TipRegion region in tipRegionCollection)
{
graphics.DrawRectangle(new Pen(Brushes.Black, 2f), region.Region);
}

}
protected override void OnMouseMove(MouseEventArgs e)
{
foreach(TipRegion region in tipRegionCollection)
{
if(region.Region.Contains(e.Location))
{
tTip.Show(region.ToolTipText, this, e.X, e.Y);
return;
}
}
if(tTip.Active)
{
tTip.Hide(this);
}
}
}

public class TipRegion
{
private readonly Rectangle region;
private readonly string toolTipText;

public TipRegion(Rectangle region, string toolTipText)
{
this.region = region;
this.toolTipText = toolTipText;
}

public string ToolTipText
{
get { return toolTipText; }
}
public Rectangle Region
{
get { return region; }
}
}


Jeremy Shovan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top