在ListView中點擊鼠標,可以通過SelectedItem屬性來獲取當前點擊了哪一個ListItem,然後通過在ListVIEw的MouseUp事件中通過判斷鼠標坐標和ColumnHeader的寬度來得知是點擊了哪一列。此方法雖然簡單,但不夠“聰明”,使用起來有局限性。
而最可行的辦法還是用API來實現。主要思路是獲取鼠標位置,將改鼠標位置轉換為窗體控件的相對位置,然後向該窗體發送LVM_SUBITEMHITTEST消息以獲取到具體的Item或者SubItem對象。
需要添加的API函數聲明:
Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Public Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Public Declare Function ScreenToClIEnt Lib "user32" (ByVal hwnd As Long, lpPoint As POINTAPI) As Long
需要增加的變量定義:
Public Type POINTAPI
x As Long
y As Long
End Type
Public Type LVHITTESTINFO
pt As POINTAPI
flags As Long
iItem As Long
iSubItem As Long
End Type
'ListVIEw所需的變量
Public Const LVM_FIRST = &H1000
Public Const LVM_SUBITEMHITTEST = (LVM_FIRST + 57)
具體程序代碼:
Private Sub ltvLog_MouseMove(Button As Integer, Shift As Integer, x As Single, y As Single)
Dim lvhti As LVHITTESTINFO
Dim iItem As Integer, iSubItem As Integer
Call GetCursorPos(lvhti.pt)
Call ScreenToClIEnt(ltvLog.hwnd, lvhti.pt)
Call SendMessage(ltvLog.hwnd, LVM_SUBITEMHITTEST, 0, lvhti.pt)
iItem = lvhti.iItem
iSubItem = lvhti.iSubItem
If iItem < 0 Then
'沒有ListItem對象
Else
If iSubItem = 0 Then
'某行第一列
Debug.print ltvLog.ListItems(iItem + 1).Text
Else
'某行第某列
Debug.print ltvLog.ListItems(iItem + 1).ListSubItems(iSubItem).Text
End If
End If
End Sub