在VB6中搜索指定字符串的listBox

6
我有一个名为lstSerial的列表框和一个名为txtSerials的文本框。我想要做的是在lstSerial中搜索txtSerials输入的字符串。我正在使用Microsoft Visual Basic 6.0中的VB6,并且找不到好的文档。
谢谢。
2个回答

8

@AlexK的回答在技术上是正确的 - 是的 - 它会起作用,但这不是首选方法。有一个专门用于此目的的API调用:

Private Declare Function SendMessage Lib "USER32" Alias "SendMessageA" _
     (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As _
     Integer, ByVal lParam As Any) As Long

'constants for searching the ListBox
Private Const LB_FINDSTRINGEXACT = &H1A2
Private Const LB_FINDSTRING = &H18F

'function to get find an item in the Listbox
Public Function GetListBoxIndex(hWnd As Long, SearchKey As String, Optional FindExactMatch As Boolean = True) As Long

    If FindExactMatch Then
        GetListBoxIndex = SendMessage(hWnd, LB_FINDSTRINGEXACT, -1, ByVal SearchKey)
    Else
        GetListBoxIndex = SendMessage(hWnd, LB_FINDSTRING, -1, ByVal SearchKey)
    End If

End Function

所以你想做这件事:

lstSerial.ListIndex = GetListBoxIndex(lstSerial.hWnd, txtSerials.Text)

Source


1
我认为这是最佳解决方案,因为它可以更快地获取列表框中的每个数据。 - Joe Kdw

6

文档;http://msdn.microsoft.com/en-us/library/aa267225(v=VS.60).aspx


(提示:此处为文档链接,需要根据实际情况进行翻译)
dim find as string,i as long,found as boolean
find=txtSerials.text

for i=0 to lstserial.listcount - 1
    if strcomp(find, lstSerial.list(i), vbTextcompare)=0 then
        found = true
        lstSerial.setfocus
        lstSerial.listindex= i
        exit for
    end if
next

if not found then msgbox "not found ..."

2
+1 我也使用这种方法,我从未发现它的性能不好,因此更喜欢它而不是API调用。 - Matt Donnan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接