How do I determine which listview column has been clicked on?
Printable View
How do I determine which listview column has been clicked on?
Would this work for you?
VB Code:
Option Explicit Private Const LVM_FIRST = &H1000 Private Const LVHT_NOWHERE As Long = &H1 Private Const LVHT_ONITEMICON As Long = &H2 Private Const LVHT_ONITEMLABEL As Long = &H4 Private Const LVHT_ONITEMSTATEICON As Long = &H8 Private Const LVHT_ONITEM As Long = (LVHT_ONITEMICON Or LVHT_ONITEMLABEL Or LVHT_ONITEMSTATEICON) Private Const LVM_SUBITEMHITTEST As Long = (LVM_FIRST + 57) Private Type POINTAPI x As Long y As Long End Type Private Type HITTESTINFO pt As POINTAPI flags As Long iItem As Long iSubItem As Long End Type Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _ (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long Dim HTI As HITTESTINFO Private Sub Form_Load() '======================= Dim i%, j% Dim itm As ListItem Dim LSI As ListSubItem ListView1.ColumnHeaders.Add , , "Item" ListView1.ColumnHeaders.Add , , "SubItem1" ListView1.ColumnHeaders.Add , , "SubItem2" ListView1.ColumnHeaders.Add , , "SubItem3" For i = 1 To 5 Set itm = ListView1.ListItems.Add(, , "Item " & i) For j = 1 To 3 Set LSI = itm.ListSubItems.Add(, , "Subitem " & i & j) Next j Next End Sub Private Sub ListView1_DblClick() '================================ Dim iRes As Long Dim iItemIndex As Long Dim iSubitemIndex As Long Dim sMsg As String On Error Resume Next iRes = SendMessage(ListView1.hwnd, LVM_SUBITEMHITTEST, 0, HTI) iItemIndex = HTI.iItem + 1 iSubitemIndex = HTI.iSubItem ListView1.ListItems(iItemIndex).Selected = True sMsg = "Selected Item: " & ListView1.ListItems(iItemIndex).Text & vbNewLine & _ "Selected SubItem: " & ListView1.ListItems(iItemIndex).SubItems(iSubitemIndex) MsgBox sMsg sMsg = "Row Index: " & iItemIndex & vbNewLine & _ "Col Index: " & iSubitemIndex + 1 & vbNewLine & _ "Col Name : " & ListView1.ColumnHeaders(iSubitemIndex + 1) MsgBox sMsg End Sub Private Sub ListView1_MouseDown(Button As Integer, Shift As Integer, x As Single, y As Single) With HTI .pt.x = (x / Screen.TwipsPerPixelX) .pt.y = (y / Screen.TwipsPerPixelY) .flags = LVHT_ONITEMICON Or LVHT_ONITEMLABEL Or LVHT_NOWHERE End With End Sub
Cool. Gonna save this code for future use. :)
Cool, indeed! Thanks a lot.
However, is it really necessary to go through all that code? What about checking (in the listview mousedown event) the x coordinate against the column boundaries, would that work?
Further, is the 9th line of the double click event handler necessary?
VB Code:
ListView1.ListItems(iItemIndex).Selected = True
I've found the code works equally well without it.
It was when I wrote it but you are free to modify it as you wish. :)Quote:
Originally Posted by krtxmrtz
Very nice! This is just what I was looking for!