Monday, May 28, 2012

Memilih Item ListBox Secara Otomatis

Bagaimana cara memilih item yang terdapat pada ListBox secara otomatis pada saat mouse berada di atasnya.
Option Explicit 

Private Declare Function
ClientToScreen Lib "user32" (ByVal hwnd As Long, 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 Declare Function
SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Long) As Long

Private Const
LB_SETCURSEL = &H186
Private Const LB_GETCURSEL = &H188

Private Type
POINTAPI
X As Long
Y As Long
End Type

Private Sub
HightLightListBox(ByVal hwndLB As Long, ByVal X As Single, ByVal Y As Single)

Dim
IndexItem As Long
Dim
Point As POINTAPI

Point.X = X \ Screen.TwipsPerPixelX
Point.Y = Y \ Screen.TwipsPerPixelY

Call
ClientToScreen(hwndLB, Point)

IndexItem = LBItemFromPt(hwndLB, Point.X, Point.Y, False)

If
IndexItem <> SendMessage(hwndLB, LB_GETCURSEL, 0, 0) Then
Call
SendMessage(hwndLB, LB_SETCURSEL, IndexItem, 0)
End If

End Sub

Contoh penggunaan kode di atas:
Private Sub Form_Load() 
Dim i As Long
For i =
0 To 100
List1.AddItem 1234567 + i
Next
End Sub

Private Sub
List1_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
HightLightListBox List1.hwnd, X, Y
End Sub