Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB4/32, VB5, VB6
Expertise: Intermediate
Jun 25, 2003



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Add Multicharacter Search Capability to Listboxes

Users often complain that listboxes don't have the same multiple keypress search capabilities as treeviews and other objects. But you can simulate this behavior by adding code to a form with a timer and a listbox whose Sorted property is set to True.

For this test, Form_Load adds some data and sets the default interval between keystrokes. You can type in "AL" to get to Allan instead of the first instance of an entry with an "a" in the list. This can be extremely helpful in long lists. You can also convert this code easily for use within a custom control:

Option Explicit

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

Private Const LB_FINDSTRING = &H18F
Private Const LB_ERR = (-1)

Private sSearchstring As String

Private Sub Form_Load()
	With List1
		.AddItem "Adam"
		.AddItem "Allan"
		.AddItem "Arty"
		.AddItem "Aslan"
		.AddItem "Barney"
		.AddItem "Bob"
	End With
	Timer1.Interval = 2000
End Sub

Private Sub List1_KeyPress(KeyAscii As Integer)
	Dim nResult As Long
	Timer1.Enabled = True
	sSearchstring = sSearchstring & Chr$(KeyAscii)
	With List1
		nResult = SendMessage(.hWnd, LB_FINDSTRING, _
			.ListIndex, ByVal sSearchstring)
		If nResult <> LB_ERR Then
			.ListIndex = nResult
			KeyAscii = 0
		End If
	End With
End Sub

Private Sub Timer1_Timer()
	sSearchstring = ""
	Timer1.Enabled = False
End Sub
Joseph L Scally
Comment and Contribute






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



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