现在的位置: 首页 > 综合 > 正文

100% .NET Control_自动完成Combobox的XComBo控件(VB.NET)

2012年11月23日 ⁄ 综合 ⁄ 共 2452字 ⁄ 字号 评论关闭

其实这类的文章在国外的技术网站上也有很多,但是都没有实现combobox的自动下拉.
在这里实现了自动下拉.
在这里我把combobox做成了一个控件(XComBo)来实现功能.它从ComboBox,可以将新建的
工程的继承改为  Inherits System.Windows.Forms.ComboBox
我认为很关键的两点是API函数SendMessage的调用和KeyPress代码段e.Handled = True的应用。
If the event is not handled, it will be sent to the operating system for default processing. Set Handled to true to cancel the KeyPress event.
Control's code:(100%原创)

  Public Class XComBo
    
Inherits System.Windows.Forms.ComboBox

#Region 
" Windows Form Designer generated code "

    Public Sub New()
        
MyBase.New()

        
'This call is required by the Windows Form Designer.
        InitializeComponent()

        
'Add any initialization after the InitializeComponent() call

    
End Sub


    
'UserControl1 overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        
If disposing Then
            
If Not (components Is NothingThen
                components.Dispose()
            
End If
        
End If
        
MyBase.Dispose(disposing)
    
End Sub


    
'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    
'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        components 
= New System.ComponentModel.Container
    
End Sub


#
End Region

    
Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal hwnd As IntegerByVal wMsg As IntegerByVal wParam As IntegerByVal lParam As IntegerAs Integer
    
Private Const CB_SHOWDROPDOWN = &H14F

    
Private Sub ComboDropdown()
        SendMessage(Handle.ToInt32, CB_SHOWDROPDOWN, 
10&)
    
End Sub


    
Protected Overrides Sub OnKeyPress(ByVal e As System.Windows.Forms.KeyPressEventArgs)

        
Dim str, strCurrentText As String

        
If ((Asc(e.KeyChar) = 13And (Asc(e.KeyChar) = 8)) Then Exit Sub

        ComboDropdown()
        strCurrentText 
= Mid(Text, 1, Text.Length - SelectedText.Length) & CStr(e.KeyChar)
        
str = CStr(strCurrentText)
        
Dim Index As Integer = FindString(str)
        
If Index >= 0 Then
            SelectedIndex 
= Index
            [
Select](str.Length, Items(Index).length - str.Length)
            e.Handled 
= True
        
End If
    
End Sub


End Class


抱歉!评论已关闭.