Show tooltips for long items in a list box


Q: How can I show tooltips for long items in a list box?

A. The following code in the MouseMove event of the ListBox will do the trick

Private Sub lstCities_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
'This procedure shows tool tips for over-long list box items
  Dim intRow As Integer
  Dim sngRowHeight As Single
  Dim sngAvailableWidth As Single

  With lstCities

    'Find the height of a row
    sngRowHeight = TextHeight(.List(0))

    'Which space is available for an item?
    If .ListCount * sngRowHeight > .Height Then

      'List box has a vertical scroll bar
      'Subtract 300 for the scroll bar
      sngAvailableWidth = .Width - 300
    Else
      '
List box has no vertical scroll bar

      '
Subtract 30 to have some margin
      sngAvailableWidth = .Width - 30
    End If

    'Which row is the mouse over?
    intRow = Y \ sngRowHeight

    If TextWidth(.List(intRow + .TopIndex)) > sngAvailableWidth Then
      'The item is too long - show it in the tooltip
      ToolTipText = .List(intRow + .TopIndex)
    Else
      'The item fits - no tooltip
      ToolTipText = ""
    End If

  End With

End Sub