| Determine which VB listbox entry lies beneath the mouse pointer Often, when you use a listbox, you might want to determine which listbox item lies beneath the mouse pointer at any given time. For instance, suppose you want to display the current entry in another listbox and dynamically change the contents as the user moves the mouse down the original list. Fortunately, you can provide this behavior with help from the SendMessage() API function and the LB_ITEMFROMPOINT constant. If you're not familiar with the SendMessage() function, it conforms to the following syntax: 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 The LB_ITEMFROMPOINT message retrieves the index of the nearest item at a specified point in a listbox control. The return value contains the appropriate zero-based index number. To use the LB_ITEMFROMPOINT message, you must declare it like so: Private Const LB_ITEMFROMPOINT = &H1A9 When using this message, you pass in the mouse pointer's current X/Y coordinates in the lParam parameter. These values must be in Pixels. Since the listbox control maintains its X/Y values in Twips, you'll need to convert these values before passing them to the API. Also, technically, the X and Y values must be in the form of low-order and high-order words. However, the Y value is really the only number you'll need to alter. To get the numbers into the proper format, use the following expression: ((YPosition * 65536) + XPosition)) Finally, when you use this expression, the SendMessage() function can return two types of values. If the function determines that the mouse pointer is over a valid listbox item, then it returns the index number of that item. If the mouse pointer isn't over an item then the function returns the high-order word value plus one (65537). With this behavior in mind, we'll want to verify the index number returned by the function. The following code shows how you can put it all together: Private Sub List1_MouseMove(Button As Integer, _ Shift As Integer, X As Single, Y As Single) Dim P As Long Dim XPosition As Long, YPosition As Long XPosition = CLng(X / Screen.TwipsPerPixelX) YPosition = CLng(Y / Screen.TwipsPerPixelY) P = SendMessage(List1.hWnd, LB_ITEMFROMPOINT, 0, ByVal _ ((YPosition * 65536) + XPosition)) If P < .ListCount Then Msgbox "The current index is: " & P End If End Sub |
Determine which VB listbox entry lies beneath the |
Express News India | Freelance ecommerce web development India