Thomas Rogeaux
Thomas Rogeaux

Reputation: 39

Getting column index of clicked column of listview

I did not find a native procedure to retrieve the index of the column, the info that is here:

ListView1.ListItems.Item (ListView1.SelectedItem.Index) .ListSubItems (HERE)

I know how to get the index of the line like this:

ListView1.SelectedItem.Index

I know how to recover the position of the mouse like this:

Private Sub ListView1_MouseUp (ByVal Button As Integer, ByVal Shift As Integer, _
                               ByVal x As stdole.OLE_XPOS_PIXELS, _
                               ByVal y As stdole.OLE_YPOS_PIXELS)

I think it should be possible to find this index. Thank you in advance for your help.

Upvotes: 3

Views: 2570

Answers (1)

Alex K.
Alex K.

Reputation: 175916

The native way is using LVM_SUBITEMHITTEST.

Module:

Private Type POINTAPI
    X As Long
    Y As Long
End Type

Private Type LVHITTESTINFO
    pt As POINTAPI
    flags As Long
    iItem As Long
    iSubItem  As Long
End Type

Private Const LVM_SUBITEMHITTEST As Long = &H1039
Private Const LVHT_ONITEM        As Long = &HE

Private Declare Function SendMessage Lib "user32" Alias "SendMessageW" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long

Form:

Private Sub yourListView_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
    Dim hitTest As LVHITTESTINFO

    With hitTest
        .flags = LVHT_ONITEM
        .pt.X = (X \ Screen.TwipsPerPixelX)
        .pt.Y = (Y \ Screen.TwipsPerPixelY)
    End With

    SendMessage yourListView.hwnd, LVM_SUBITEMHITTEST, 0, hitTest

    If (hitTest.iItem < 0) Then Exit Sub

    If hitTest.iSubItem = 0 Then
        MsgBox yourListView.ListItems(hitTest.iItem + 1).Text
    Else
        MsgBox yourListView.ListItems(hitTest.iItem + 1).SubItems(hitTest.iSubItem)
    End If
End Sub

Upvotes: 1

Related Questions