How do I capture the enter key in a windows forms combobox

前端 未结 7 527
盖世英雄少女心
盖世英雄少女心 2021-01-07 21:33

How do I capture the enter key in a windows forms combo box when the combobox is active?

I\'ve tried to listen to KeyDown and KeyPress and I\'ve created a subclass a

相关标签:
7条回答
  • 2021-01-07 21:52

    Hook up the KeyPress event to a method like this:

    protected void myCombo_OnKeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == 13)
        {
            MessageBox.Show("Enter pressed", "Attention");                
        }
    }
    

    I've tested this in a WinForms application with VS2008 and it works.

    If it isn't working for you, please post your code.

    0 讨论(0)
  • 2021-01-07 21:55

    In case you define AcceptButton on your form, you cannot listen to Enter key in KeyDown/KeyUp/KeyPress.

    In order to check for that, you need to override ProcessCmdKey on FORM:

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
        if ((this.ActiveControl == myComboBox) && (keyData == Keys.Return)) {
            MessageBox.Show("Combo Enter");
            return true;
        } else {
            return base.ProcessCmdKey(ref msg, keyData);
        }
    }
    

    In this example that would give you message box if you are on combo box and it works as before for all other controls.

    0 讨论(0)
  • 2021-01-07 21:56
    private void comboBox1_KeyDown( object sender, EventArgs e )
    {
       if( e.KeyCode == Keys.Enter )
       {
          // Do something here...
       } else Application.DoEvents();
    }
    
    0 讨论(0)
  • 2021-01-07 21:57

    Try this:

    protected override bool ProcessCmdKey(ref Message msg, Keys k)
    {
        if (k == Keys.Enter || k == Keys.Return)
        {
            this.Text = null;
            return true;
        }
    
        return base.ProcessCmdKey(ref msg, k);
    }
    
    0 讨论(0)
  • 2021-01-07 22:01

    or altertatively you can hook up the KeyDown event:

    private void comboBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            MessageBox.Show("Enter pressed.");
        }
    }
    
    0 讨论(0)
  • 2021-01-07 22:02
    protected void Form_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == 13)  // or Key.Enter or Key.Return
        {
            MessageBox.Show("Enter pressed", "KeyPress Event");                
        }
    }
    

    Don't forget to set KeyPreview to true on the form.

    0 讨论(0)
提交回复
热议问题