devxlogo

Determine List Item by Coordinates

Determine List Item by Coordinates

I wanted users to be able to get a definition for each item in a list box by right-clicking on the item. Unfortunately, right-clicking doesn’t automatically select the item, so you need some other way of knowing your location in the list box. Simply reading the Y value from the MouseDown event and converting that value to a line number will work, unless the user scrolls the list. I used the SendMessage API, which can get information from controls, to solve the problem. Here’s the code:

 		'Declarations section		Private Declare Function SendMessage Lib "user32" _			Alias "SendMessageA" (ByVal hWnd As Long, ByVal _			wMsg As Long, ByVal wParam As Long, lParam As _			Any) As LongConst LB_GETITEMHEIGHT = &H1A1'value to get height of one line in listbox		'listbox codePrivate Sub List1_MouseDown(Button As Integer, Shift As _	Integer, X As Single, Y As Single)	Dim msg As String	Dim TopIndex As Long	Dim CharHeight As Long	Dim CurIndex As Long	With List1		'find height of one line in listbox		CharHeight = SendMessage(.hWnd, LB_GETITEMHEIGHT, _			0, 0)		'function returns height in pixels so convert to 		'twips		CharHeight = CharHeight * Screen.TwipsPerPixelY		If Button = 2 Then 'right click			'find index number of item that received right 			'click			CurIndex = Y  CharHeight + .TopIndex			'If index number is valid then display information			If CurIndex 

If the items in your list box are always displayed in the same order and no deletions occur, then all you need is an array of definitions that correspond to each item in the list box. To retrieve the appropriate definition, use this code:

 	msg = DefinitionArray(CurIndex)

After displaying the definition in a window, you only need code for the list-box MouseUp event:

 	If Button = 2 Then frmInfo.Hide

devx-admin

Share the Post: