使用HitTestInfo查找listview列索引

问题描述 投票:1回答:4

当我使用以下代码右键单击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),我只是找不到它的列索引...

.net vb.net listview hittest
4个回答
2
投票

不幸的是,使用Alex提供的上述代码,如果一行中有多个子项包含相同的文本值,则存在危险,那么它将选择第一个最左列索引。更好的方法是复制下面的函数,它只使用鼠标指针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

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将导致无法使用任何项目。


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检测到的文本进行比较


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.