0

如何实现与多个键一起使用的搜索功能CheckedListBoxListBox

示例:我在列表中有以下项目:

1000 1500 1520 2010 5001 5102

当我按下键 1 时,立即搜索与第一个以“1”开头的字符匹配的第一个匹配项。

但是,如果我想定位项目“5102”,列表只能搜索到 5,然后,我需要手动去识别想要的项目。

4

2 回答 2

0

回答我自己的问题。这是一个不需要太多工作的干净解决方案(所有代码都可以在 KeyDown 事件中处理):

Sub DropDownListBox_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)
    If Char.IsLetterOrDigit(Chr(e.KeyValue)) Then
        e.SuppressKeyPress = True
        If TryCast(sender.tag, Timer) Is Nothing Then
            Dim vTimer As New Timer

            vTimer.Interval = 1000
            vTimer.Tag = ""
            sender.Tag = vTimer

            AddHandler vTimer.Tick,
                Sub(Timer As Object, eventsArgs As System.EventArgs)
                    Timer.Tag = ""

                    If Not TryCast(sender, CheckedListBox).Visible Then
                        Timer.dispose() : Timer = Nothing
                    End If
                End Sub
        Else
            sender.Tag.Stop() : sender.Tag.Start()
            sender.Tag.Tag &= Chr(e.KeyValue)

            Dim vIndex As Integer = TryCast(sender, CheckedListBox).FindString(sender.Tag.Tag)

            If vIndex <> -1 Then TryCast(sender, CheckedListBox).SelectedItem = TryCast(sender, CheckedListBox).Items(vIndex)
        End If
    End If
End Sub

基本上我使用 TAG 对象来保持 Timer 每 1 秒运行一次;然后,如果用户键入多个字符,该过程将准确找到所需的文本。

欢迎任何评论或反馈。

于 2013-02-22T17:17:47.963 回答
-1
Public Class Form1
    Dim Type As String
    Private Sub ListBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles ListBox1.KeyPress
        If Asc(e.KeyChar) <> 8 Then
            If Asc(e.KeyChar) < 65 Or Asc(e.KeyChar) > 122 Then
                e.Handled = True
                ' Clear String at Escape key press & Reset Listbox location
                If Asc(e.KeyChar) = 27 Then
                    Type = ""
                    ListBox1.SelectedIndex = -1
                    ListBox1.SelectedItem = ListBox1.SelectedIndex
                End If
            End If
            If Asc(e.KeyChar) = 27 Then
                ' Do not add escape key char to string at key press
            Else
                ' add char one by one after key press
                Type &= e.KeyChar
                Dim TL As Integer = Type.Length
                Dim i As Integer = 0
                For i = 0 To ListBox1.Items.Count - 1
                    ' match key press in total items in listbox
                    'MsgBox(Format$(Mid$(ListBox1.Items(i), 1, TL)))
                    If Format$(Mid$(ListBox1.Items(i), 1, TL)) = Type Then
                        ListBox1.SelectedIndex = i
                    End If
                Next
            End If
        End If
    End Sub
End Class
于 2016-01-01T12:00:59.323 回答