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

前端 未结 5 1951
无人共我
无人共我 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条回答
  •  不思量自难忘°
    2021-02-19 03:51

    I had the ESC problem on a DropDownList-style combobox. I slightly modified what worked for me to accommodate your needs:

    public class MyComboBox : System.Windows.Forms.ComboBox
    {
      private bool _sendSic;
    
      protected override void OnPreviewKeyDown(System.Windows.Forms.PreviewKeyDownEventArgs e)
      {
        base.OnPreviewKeyDown(e);
    
        if (DroppedDown)
        {
          switch(e.KeyCode)
          {
            case System.Windows.Forms.Keys.Escape:
              _sendSic = true;
              break;
            case System.Windows.Forms.Keys.Tab:
            case System.Windows.Forms.Keys.Enter:
              if(DropDownStyle == System.Windows.Forms.ComboBoxStyle.DropDown)
                _sendSic = true;
              break;
          }
        }
      }
    
      protected override void OnDropDownClosed(System.EventArgs e)
      {
        base.OnDropDownClosed(e);
    
        if(_sendSic)
        {
          _sendSic = false;
          OnSelectedIndexChanged(System.EventArgs.Empty);
        }
      }
    }
    

    What this does is listening to keystrokes that come in while the dropdown is open. If it's ESC, TAB or ENTER for a DropDown-style ComboBox or ESC for a DropDownList-style ComboBox, a SelectedIndexChanged-Event is triggered when the DropDown is closed.
    I have never ever used ComboBoxStyle.Simple and don't really know how it does or should work, but since it to the best of my knowledge never displays a DropDown, this should be safe even for that style.

    If you don't want to derive from ComboBox to build your own control, you can also apply similar logic to a ComboBox on a form by subscribing to it's PreviewKeyDown and DropDownClosed events.

提交回复
热议问题