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

前端 未结 7 528
盖世英雄少女心
盖世英雄少女心 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 22:10

    It could be that your dialog has a button that's eating the enter key because it's set to be the AcceptButton in the form property.
    If that's the case then you solve this like this by unsetting the AcceptButton property when the control gets focus then resetting it back once the control loses focus ( in my code, button1 is the accept button )

    private void comboBox1_Enter(object sender, EventArgs e)
    {
        this.AcceptButton = null;
    }
    
    private void comboBox1_Leave(object sender, EventArgs e)
    {
        this.AcceptButton = button1;
    }
    
    private void comboBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                MessageBox.Show("Hello");
            }
        }
    

    I have to admit not liking my own solution as it seems a little hacky to unset/set the AcceptButton property so if anyone has a better solution then I'd be interested

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