What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleMake an OwnerDraw tooltip that displays an image in Visual Basic 2005
DescriptionThis example shows how to make an OwnerDraw tooltip that displays an image in Visual Basic 2005. Unfortunately this won't work in earlier versions of Visual Basic.
KeywordsOwnerDraw tooltip, tooltip, image, picture, VB 2005
CategoriesVB.NET, Controls
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 Sub tipButtons_Popup(ByVal sender As Object, ByVal _
    e As System.Windows.Forms.PopupEventArgs) Handles _
    Dim wid As Integer = e.ToolTipSize.Width + 50
    Dim hgt As Integer = e.ToolTipSize.Height
    If hgt < 50 Then hgt = 50
    e.ToolTipSize = New Size(wid, hgt)
End Sub
When the tooltip is displayed, the following Draw event handler executes. It 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 My.Resources.happy.

' Draw the tooltip.
Private Sub tipButtons_Draw(ByVal sender As Object, ByVal e _
    As System.Windows.Forms.DrawToolTipEventArgs) Handles _
    ' Draw the background and border.

    ' Draw the text.
    Using sf As New StringFormat()
        sf.Alignment = StringAlignment.Near
        sf.LineAlignment = StringAlignment.Center
        Dim rect As New Rectangle(50, 0, e.Bounds.Width - _
            50, e.Bounds.Height)
        e.Graphics.DrawString(e.ToolTipText, e.Font, _
            Brushes.Green, rect, sf)
    End Using

    ' Draw the image.
    e.Graphics.DrawImage(My.Resources.happy, 9, 9)
End Sub
Copyright © 1997-2006 Rocky Mountain Computer Consulting, Inc.   All rights reserved.