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 < .ListCount Then				'Code to retrieve and display item definition				'goes here. Mine looks like this.				msg = GetMessage(.List(CurIndex))				frmInfo.Label1.Caption = msg				frmInfo.Show			End If		End If	End WithEnd Sub

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
See also  Why ChatGPT Is So Important Today

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist