Option Explicit
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Copyright ©1996-2011 VBnet/Randy Birch, All Rights Reserved.
' Some pages may also contain other copyrights by the author.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Distribution: You can freely use this code in your own
' applications, but you may not reproduce
' or publish this code on any web site,
' online service, or distribute as source
' on any media without express permission.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Private Type POINTAPI
X As Long
Y As Long
End Type
Private Declare Function LBItemFromPt Lib "comctl32" _
(ByVal hwnd As Long, _
ByVal ptx As Long, _
ByVal pty As Long, _
ByVal bAutoScroll As Long) As Long
Private Declare Function ClientToScreen Lib "user32" _
(ByVal hwnd As Long, lpPoint As POINTAPI) As Long
Private Sub Command1_Click()
Unload Me
End Sub
Private Sub Form_Load()
'Add a few items
Dim i As Integer
For i = 0 To 20
List1.AddItem "List item no" & Str$(i)
Next
End Sub
Private Sub List1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
If Button = vbRightButton Then
Dim curritem As Long
Dim pt As POINTAPI
'adjust to the expected values
pt.x = X \ Screen.TwipsPerPixelX
pt.y = Y \ Screen.TwipsPerPixelY
'and map to the client coordinates
Call ClientToScreen(List1.hwnd, pt)
'get the item nearest the cursor
curritem = LBItemFromPt(List1.hwnd, pt.X, pt.Y, False)
If curritem > -1 Then
Text1.Text = "Right-mouse clicked over item " & _
curritem & " - " & vbTab & Chr$(34) & _
List1.List(curritem) & Chr$(34)
'this line selects the item (if desired)
'with the right-click
List1.Selected(curritem) = True
'uncomment to display a context menu which
'could be customized for the given selection
'PopupMenu mnuListOptions
End If
End If
End Sub |
Run the project and click a list item .... it will become
selected, and its index and text will be reflected in the listbox.
By moving or copying the code to the List1_MouseMove event, removing
the If .. Then statement, and commenting out the List1.Selected() statement, the textbox will now reflect the item the mouse is currently
over - great for displaying in a status bar! |