PDA

Click to See Complete Forum and Search --> : Hover over listbox and show value


BenJones
Apr 12th, 2010, 08:32 AM
This little sniplet of code allows you to hover over a listbox and select the item the mouse is over and also show the items value. It may also come in handy if you want to show a tooltip text of the item your over. Hope it maybe usfull.

You need to place a listbox and a label control on your form, Then paste the code below in to the general selection of your form.

Private Declare Function GetScrollPos Lib "user32.dll" (ByVal hwnd As Long, ByVal nBar As Long) As Long

Private Sub Form_Load()
Dim X As Integer

'Add some items to a listbox
For X = 0 To 50
Call List1.AddItem("This item index is: " & CStr(X))
Next X

List1.FontSize = 18
Set Me.Font = List1.Font

End Sub

Private Sub List1_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
Dim yPos As Long

'Get Item Position in the list
yPos = (Y \ Me.TextHeight("A")) + GetScrollPos(List1.hwnd, &H1)

'Move to the list index
List1.ListIndex = yPos
'Show listbox index value in label
Label1.Caption = List1.List(yPos)

End Sub

VBClassicRocks
Apr 13th, 2010, 07:37 AM
Ben, thanks for sharing. One item: this only works if the Listbox has
the same font as the form. Here's some code for HitTesting a ListBox:


Option Explicit
Private Type POINTAPI
X As Long
Y As Long
End Type
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Private Declare Function LBItemFromPt Lib "comctl32.dll" (ByVal hLB As Long, ByVal ptx As Long, ByVal pty As Long, ByVal bAutoScroll As Long) As Long

Private Function HitTest(ByVal LWnd As Long) As Long
'returns -1 for blank area
Dim pt As POINTAPI
GetCursorPos pt
HitTest = LBItemFromPt(List1.hwnd, pt.X, pt.Y, False)
End Function

Private Sub Form_Load()
Dim i As Long
For i = 1 To 10
List1.AddItem "Item " & i
Next
End Sub

Private Sub List1_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
Dim yPos As Long
yPos = HitTest(List1.hwnd)
If yPos > -1 Then
List1.ListIndex = yPos
Label1.Caption = List1.List(yPos)
End If
End Sub

LaVolpe
Apr 13th, 2010, 09:07 AM
Ben, VBClassicRocks' comments are valid.
I thought I add this: One can set the form's Font to the listbox's Font, permanently/temporarily before calling your routine.
Also, you shouldn't need to call GetScrollPos. You could use the listbox's .TopIndex property instead, and you'd have an API-less solution.

BenJones
Apr 13th, 2010, 10:28 AM
Thanks for the code VBClassicRocks, Thanks LaVolpe i did not know about the TopIndex property