Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Listview control how to get column index

Status
Not open for further replies.

sexydog

Programmer
Jul 9, 2002
176
GB
Hi

I am using a listview control in my application. what i need is the column index when i click on a row. how do i get this


Many Thanks
 
That was a bit tricky and interesting question, but I managed to get it done.

You can use the following GetLVColIndex function to get the column index of a listview passing the X mouse coordinate as argument.
___
[tt]
Option Explicit
Private Declare Function GetWindow Lib "user32" (ByVal hwnd As Long, ByVal wCmd As Long) As Long
Private Declare Function GetWindowRect Lib "user32" (ByVal hwnd As Long, lpRect As RECT) As Long
Private Declare Function ScreenToClient Lib "user32" (ByVal hwnd As Long, lpPoint As POINTAPI) As Long
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

Const GW_CHILD = 5

Const HDM_FIRST = &H1200
Const HDM_HITTEST = (HDM_FIRST + 6)

Private Type POINTAPI
x As Long
y As Long
End Type

Private Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type

Private Type HD_HITTESTINFO
pt As POINTAPI
flags As Long
iItem As Long
End Type

Function GetLVColIndex(LV As ListView, ByVal TwipsX As Long) As Long
Dim hHdr As Long
hHdr = GetWindow(LV.hwnd, GW_CHILD)

Dim rc As RECT
GetWindowRect hHdr, rc

Dim pt As POINTAPI
pt.x = rc.Left
ScreenToClient LV.hwnd, pt

pt.x = TwipsX \ Screen.TwipsPerPixelX - pt.x
pt.y = (rc.Bottom - rc.Top) \ 2

Dim hti As HD_HITTESTINFO
hti.pt = pt
SendMessage hHdr, HDM_HITTEST, 0, hti

GetLVColIndex = hti.iItem + 1
End Function

Private Sub ListView1_MouseUp(Button As Integer, Shift As Integer, x As Single, y As Single)
Debug.Print GetLVColIndex(ListView1, x)
End Sub[/tt]
___

The function GetLVColIndex returns a 1-based index of the column from the x coordinate passed as argument. The return value is 0 if no column lies at the specifed x offset.

Note that this code works only if you have configured your listview to use column headers. If the column headers are not used (i.e. HideColumnHeaders property is True) then the function will fail to report the correct column index.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top