鼠标移动ListBox上的句柄

时间:2013-11-13 22:32:25

标签: visual-studio-2010 listbox listboxitem

我有一个ListBox,我想在其上处理mousemove事件;因此我使用以下代码

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

我的问题是......当我不移动鼠标时,此程序始终在执行时运行 g.MeasureString(s, myLB.Font).Width > myLB.ClientRectangle.Width
为什么会发生这种情况,我该如何避免呢。

1 个答案:

答案 0 :(得分:1)

你可以做的只是设置工具提示,如果它不是你想要的值:

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