Question

I have a ListBox on which I want to handle the mousemove event; And for that reason I'm using the following code

Private Sub AreaLB_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles AreaLB.MouseMove
        Dim ListMousePosition As Point = AreaLB.PointToClient(Me.MousePosition)
        Dim itemIndex As Integer = AreaLB.IndexFromPoint(ListMousePosition)
        Dim AreaToolTip As ToolTip = ToolTip1
        Dim myLB As ListBox = AreaLB
        AreaToolTip.Active = True
        Dim g As Graphics = AreaLB.CreateGraphics()
        If itemIndex > -1 Then
            Dim s As String = myLB.Items(itemIndex)
            If g.MeasureString(s, myLB.Font).Width > myLB.ClientRectangle.Width Then
                AreaToolTip.SetToolTip(myLB, s)
            Else
                AreaToolTip.SetToolTip(myLB, "")
            End If
            g.Dispose()
        End If
    End Sub

My problem is... When I'm not moving the mouse this procedure runs always when the
g.MeasureString(s, myLB.Font).Width > myLB.ClientRectangle.Width
Why that happens and how can I avoid it.

Was it helpful?

Solution

What you can do is only set the ToolTip if it isn't already the value you want it to be:

Private Sub AreaLB_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles AreaLB.MouseMove
    ToolTip1.Active = True
    Dim itemIndex As Integer = AreaLB.IndexFromPoint(e.X, e.Y)
    If itemIndex > -1 Then
        Using g As Graphics = AreaLB.CreateGraphics()
            Dim s As String = AreaLB.Items(itemIndex)
            If g.MeasureString(s, AreaLB.Font).Width > AreaLB.ClientRectangle.Width Then
                If ToolTip1.GetToolTip(AreaLB) <> s Then
                    ToolTip1.Show(s, AreaLB)
                End If
            Else
                ToolTip1.Show("", AreaLB)
            End If
        End Using
    End If
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top