How to set tooltips on ListView Subitems in .Net

后端 未结 5 1252
轻奢々
轻奢々 2021-02-10 09:15

I am trying to set the tool tip text for some of my subitems in my listview control. I am unable to get the tool tip to show up.

Anyone have any suggestions?

         


        
5条回答
  •  醉话见心
    2021-02-10 09:41

    The original code in the question does not work since it creates a New ToolTip inside OnMouseMove. I guess that the ToolTip.Show method is asynchronous and thus the function exits immediately after invoking it, destroying the temporary ToolTip. When Show gets to execute, the object does not exist anymore.

    The solution would be to create a persistent ToolTip object, by:

    1. a ToolTip control on the form; or
    2. a private ToolTip class field (disposed in the Finalize or Dispose method of the class); or
    3. a Static object inside the function.

    Also, there is no need to GetItemAt() since ListViewHitTestInfo already contains both the item and subitem references.
    Improving Colin's answer, here is my code:

    Private Sub ListView_MouseMove(sender As Object, e As MouseEventArgs) _
    Handles MyList1.MouseMove
        Static prevMousePos As Point = New Point(-1, -1)
    
        Dim lv As ListView = TryCast(sender, ListView)
        If lv Is Nothing Then _
            Exit Sub
        If prevMousePos = MousePosition Then _
            Exit Sub  ' to avoid annoying flickering
    
        With lv.HitTest(lv.PointToClient(MousePosition))
            If .SubItem IsNot Nothing AndAlso Not String.IsNullOrEmpty(.SubItem.Text) Then
                'AndAlso .Item.SubItems.IndexOf(.SubItem) = 1
                '...when a specific Column is needed
    
                Static t As ToolTip = toolTip1  ' using a form's control
                'Static t As New ToolTip()      ' using a private variable
                t.ShowAlways = True
                t.UseFading = True
                ' To display at exact mouse position:
                t.Show(.SubItem.Tag, .Item.ListView, _
                       .Item.ListView.PointToClient(MousePosition), 2000)
                ' To display beneath the list subitem:
                t.Show(.SubItem.Tag, .Item.ListView, _
                       .SubItem.Bounds.Location + New Size(7, .SubItem.Bounds.Height + 1), 2000)
                ' To display beneath mouse cursor, as Windows does:
                ' (size is hardcoded in ugly manner because there is no easy way to find it)
                t.Show(.SubItem.Tag, .Item.ListView, _
                       .Item.ListView.PointToClient(Cursor.Position + New Size(1, 20)), 2000)
            End If
            prevMousePos = MousePosition
        End With        
    End Sub
    

    I've made the code as general as possible so that the function could be assigned to multiple ListViews.

提交回复
热议问题