Combobox 自动补全

来源:互联网 发布:mac 终端切换用户 编辑:程序博客网 时间:2024/04/30 06:59

 Private Sub ComboBox1_KeyUp(ByVal sender As Object, _
        ByVal e As System.Windows.Forms.KeyEventArgs) Handles ComboBox1.KeyUp
        AutoCompleteKeyUp(ComboBox1, e)
    End Sub

    Public Sub AutoCompleteKeyUp(ByVal Combo As ComboBox, ByVal e As KeyEventArgs)
        Dim strTyped As String
        Dim intFoundIndex As Integer
        Dim objFoundItem As Object
        Dim strFoundText As String
        Dim strAppendText As String
        '忽略这些基本操作键
        Select Case e.KeyCode
            Case Keys.Back, Keys.Left, Keys.Right, Keys.Up, _
                Keys.Delete, Keys.Down, Keys.CapsLock
                Return
        End Select
        '看看用户输入了些什么
        strTyped = Combo.Text
        intFoundIndex = Combo.FindString(strTyped)
        '如果找到了的话……
        If intFoundIndex >= 0 Then
            '获取Combo下的匹配项
            objFoundItem = Combo.Items(intFoundIndex)
            '获取匹配的字符串
            strFoundText = Combo.GetItemText(objFoundItem)
            '开始自动添加文本
            strAppendText = strFoundText.Substring(strTyped.Length)
            Combo.Text = strTyped & strAppendText
            '选亮添加的文本
            Combo.SelectionStart = strTyped.Length
            Combo.SelectionLength = strAppendText.Length
        End If
    End Sub

原创粉丝点击