ITEEDU

自建AutoCompleteComboBox类

using System;
using System.Windows.Forms;



namespace ComboBoxTest
{
    class AutoCompleteComboBox : ComboBox
    {
        // Track if a special key is pressed
        // (in which case the text replacement operation will be skipped).
        private bool controlKey = false;

        // Determine whether a special key was pressed.
        protected override void OnKeyPress(
        System.Windows.Forms.KeyPressEventArgs e)
        {

            base.OnKeyPress(e);

            if (e.KeyChar == (int)Keys.Escape)
            {

                // Clear the text.
                this.SelectedIndex = -1;
                this.Text = "";
                controlKey = true;
            }
            else if (Char.IsControl(e.KeyChar))
            {

                controlKey = true;
            }
            else
            {

                controlKey = false;
            }
        }

        // Perform the text substitution.
        protected override void OnTextChanged(System.EventArgs e)
        {

            base.OnTextChanged(e);

            if (this.Text != "" && !controlKey)
            {

                // Search for a matching entry.
                string matchText = this.Text;
                int match = this.FindString(matchText);

                // If a matching entry is found, insert it now.
                if (match != -1)
                {

                    this.SelectedIndex = match;

                    // Select the added text so it can be replaced
                    // if the user keeps typing.
                    this.SelectionStart = matchText.Length;
                    this.SelectionLength = this.Text.Length - this.SelectionStart;
                }
            }
        }

    }
}