Make an owner drawn tooltip that displays a picture in C#

Add a Tooltip component to the form. At design time, set the Tooltip's OwnerDraw property to True.

The Tooltip's Draw event handler must draw the tip. That routine cannot set the size of the tooltip's area, but the component's Popup event handler can.

The following code executes before the tooltip appears. To make room for the image, this code adds 50 to the tooltip's initial width and ensures that the area is at least 50 pixels tall.

// Set the tooltip's bounds.
private void tipButtons_Popup(object sender, PopupEventArgs e)
{
int wid = e.ToolTipSize.Width + 50;
int hgt = e.ToolTipSize.Height;
if (hgt < 50) hgt = 50;
e.ToolTipSize = new Size(wid, hgt);
}

When the tooltip is displayed, the following Draw event handler executes.

// Draw the tooltip.
private void tipButtons_Draw(object sender, DrawToolTipEventArgs e)
{
// Draw the background and border.
e.DrawBackground();
e.DrawBorder();

// Draw the text.
using (StringFormat sf = new StringFormat())
{
sf.Alignment = StringAlignment.Near;
sf.LineAlignment = StringAlignment.Center;
Rectangle rect = new Rectangle(
50, 0, e.Bounds.Width - 50, e.Bounds.Height);
e.Graphics.DrawString(
e.ToolTipText, e.Font, Brushes.Green, rect, sf);
}

// Draw the image.
e.Graphics.DrawImage(Properties.Resources.happy, 9, 9);
}

This code uses the DrawToolTipEventArgs parameter's DrawBackground and DrawBorder methods to draw the normal tooltip background and border. It then uses the e.Graphics object's DrawString method to draw the tooltip's text. It draws the text in a rectangle that occupies the tooltip's area except for the left 50 pixels. The code uses a StringFormat object to make the text left-aligned and centered vertically in that area.

Finally the code uses the e.Graphics object's DrawImage method to draw the picture stored in Properties.Resources.happy.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.