列表框多个KeyPress

时间:2013-02-22 17:17:48

标签: vb.net listbox checkedlistbox

如何在CheckedListBoxListBox中实现适用于多个键的搜索功能?

示例:列表中包含以下项目:

1000 1500 1520 2010 5001 5102

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

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

2 个答案:

答案 0 :(得分: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秒运行一次;然后,如果用户键入几个字符,该过程将找到所需的文本。

欢迎任何评论或反馈。

答案 1 :(得分:-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