WinForms ComboBox SelectedIndexChanged not firing when typing few chars followed by Alt+Down

前端 未结 5 1979
无人共我
无人共我 2021-02-19 03:21

In short

When I type a character in a ComboBox, press Alt+Down followed by Enter or Tab, the SelectedIndexChanged event doesn\'t fire, even though the S

5条回答
  •  猫巷女王i
    2021-02-19 03:58

    I ended up deriving my own class from ComboBox:

    public class EditableComboBox : ComboBox
    {
        protected int backupIndex;
        protected string backupText;
    
        protected override void OnDropDown(EventArgs e)
        {
            backupIndex = this.SelectedIndex;
            if (backupIndex == -1) backupText = this.Text;
            else backupText = null;
            base.OnDropDown(e);
        }
    
        protected override void OnSelectionChangeCommitted(EventArgs e)
        {
            backupIndex = -2;
            base.OnSelectionChangeCommitted(e);
        }
    
        protected override void OnSelectionIndexChanged(EventArgs e)
        {
            backupIndex = -2;
            base.OnSelectionIndexChanged(e);
        }
    
        protected override void OnDropDownClosed(EventArgs e)
        {
            if (backupIndex > -2 && this.SelectedIndex != backupIndex)
            {
                if (backupIndex > -1)
                {
                    this.SelectedIndex = backupIndex;
                }
                else
                {
                    string oldText = backupText;
                    this.SelectedIndex = -1;
                    this.Text = oldText;
                    this.SelectAll();
                }
            }
            base.OnDropDownClosed(e);
        }
    }
    

提交回复
热议问题