使用HitTestInfo查找listview列索引

时间:2013-03-26 15:48:49

标签: .net vb.net listview hittest

当我使用此代码右键单击listview项目时,我正在寻找列的索引:

Private Sub Source_lvArticles_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Source_lvArticles.MouseDown
    If e.Button = System.Windows.Forms.MouseButtons.Right Then
        Sources_RightClickedCol = 0

        Dim info As ListViewHitTestInfo = Source_lvArticles.HitTest(e.X, e.Y)
        Sources_RightClickedCol = info.Location
    End If
End Sub

我能够找到我正确点击的项目的文本(info.Subitem.Text),我只是找不到它的列索引......

4 个答案:

答案 0 :(得分:2)

不幸的是,使用Alex提供的上述代码,如果一行中有多于1个子项包含相同的文本值,那么它将存在选择第一个最左列索引的危险。更好的方法是复制下面的函数,它只是使用鼠标指针X值并将其与列右值进行比较,其中X超过此时我们在循环计数上有整数:

Private Function GetColumnIndex(ByVal lvw As ListView, ByVal MouseX As _
Integer) As Integer

    Dim result As Integer = 0

    'Get the right and width pixel values of all the columns 
    Dim ColW As New List(Of Integer)
    Dim Index As Integer = 0


    For Each col As ColumnHeader In lvw.Columns
        ColW.Add(col.Width)
        Dim X As Integer = 0
        For i As Integer = 0 To ColW.Count - 1
            X += ColW(i)
        Next

        'Once you have the rightmost values of the columns 
        'just work out where X falls in between

        If MouseX <= X Then
            result = Index
            Exit For
        End If

        Index += 1

    Next

    Return result
End Function

答案 1 :(得分:2)

有一个很多更简单的方式来点击“列”:

Private Function GetSubItemIndexAt(x As Integer, y As Integer) As Integer
    ' get HitTextinfo for X,Y
    Dim ht As ListViewHitTestInfo = myLV.HitTest(x, y)

    If ht.Item IsNot Nothing Then
        ' use built in method to get the index
        Return ht.Item.SubItems.IndexOf(ht.SubItem)
    End If

    Return -1           ' (semi) universal not found indicator

End Function

请注意,索引0将引用ItemLabel区域。

唯一需要注意的是HitTest仅适用于有实际物品的地方。如果单击非项目区域(例如下面的空白区域),则该XY将导致无法使用任何项目。

答案 2 :(得分:0)

对于那些想知道我做了什么来弄清楚我的列索引的人...它不是很优雅,但它确实有效。

Private Sub Source_lvArticles_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Source_lvArticles.MouseDown
    If e.Button = System.Windows.Forms.MouseButtons.Right Then
        Sources_RightClickedCol = 0

        Dim info As ListViewHitTestInfo = Source_lvArticles.HitTest(e.X, e.Y)
        Dim SubItem As String = info.SubItem.Text

        For Each item As ListViewItem In Source_lvArticles.Items
            Dim i As Integer = 1
            Dim found As Boolean = False
            For Each s As ListViewItem.ListViewSubItem In item.SubItems
                If s.Text = SubItem Then
                    Sources_RightClickedCol = i
                    found = True
                    Exit For
                End If
                i += 1
            Next
            If found Then Exit For
        Next
    End If
End Sub

这样做是通过列表视图中每行的每个子项并保持列索引(i)的计数。它将当前子项的文本与HitTest检测到的子文本

进行比较

答案 3 :(得分:0)

您还可以在填充列表视图时使用subitem.tag属性存储有关列的信息,然后稍后使用hittest。(e.X,e.Y).SubItem.tag检索该信息。