Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Visual Basic
Expertise: Intermediate
Jan 13, 1999

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 Long
Const LB_GETITEMHEIGHT = &H1A1
'value to get height of one line in listbox

		'listbox code
Private 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 With
End 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
Kevin W.
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date