'=========================================================================== ' Subject: FIND LISTBOX ITEM W/SENDMESSAGE Date: 03-13-99 (19:09) ' Author: MS Knowledge Base Code: VBWIN ' Origin: CapeCanaveral/Lab/1961/ Packet: VBWIN.ABC '=========================================================================== Finding Listbox Items Using SendMessage Applies to: VB4-32 With appropriate API 16-bit API declarations, this code also applies to: VB3 VB4-16 ------------------------------------------------------------------------ There may be times when, through code, you wish to select or highlight a specific entry in a listbox. Using the Windows API, this is easily accomplished. Place the following API declare code into the general declarations area of a bas module: Public Declare Function SendMessageStr Lib "user32" Alias "SendMessageA" _ (ByVal hwnd As Long, _ ByVal wMsg As Long, _ ByVal wParam As Long, _ ByVal lParam As String) As Long Public Const LB_FINDSTRING = &H18F Public Const LB_FINDSTRINGEXACT = &H1A2 Add a textbox and listbox to a form. 'add this code to the form load to fill a list with some (15) of the system's screen fonts. Sub Form_Load() Dim i As Integer, max As Integer max = Screen.FontCount If max > 15 Then max = 15 For i = 1 To max List1.AddItem Screen.Fonts(i) Next End Sub 'Add the following to the textbox _Change sub Private Sub Text1_Change() On Error Resume Next List1.ListIndex = SendMessageStr(List1.hwnd, LB_FINDSTRING, 0&, (Text1)) End Sub Run the project, and begin to type a fontname into the textbox. If there is a font beginning with the entered text, it will be selected. ------------------------------------------------------------------------ Comments The return value of the call is the listindex of the matching item, or -1 if a match is not found. Remember too that whenever code sets the ListIndex property, it causes a List_Click event to fire. If this is undesireable, appropriate flags need to be implemented. If the constant used in the API call is LB_FINDSTRING, any partial match beginning with the entered string is located. If the constant LB_FINDSTRINGEXACT is used, then (obviously) the entered text much match exactly the string in the listbox. LB_FINDSTRINGEXACT is most useful when attempting to determine if a *specific* string is in a listbox. To pass the contents of a textbox to an API, enclose the property in brackets. This assures that the actual text, and not the text property, are passed. In addition, because the text property is the default property of a textbox, it is unnecessary to specify the .Text property when passing the value. This rule holds true for any property's default value.