VBGood网站全文搜索 Google

首页 - 经验之谈 - 确定哪一个listbox的那一条在当前鼠标下
发表评论(0)作者:不详, 平台:VB6.0+Win98, 阅读:11138, 日期:2001-02-07
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

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