Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How Do I Capture the Enter Key in a Windows Forms Combobox

0.00/5 (No votes)
25 Jul 2017 1  
Quick tip for capture ENTER key in a Windows Form combobox

Difficult Problems, Easy Solutions

Today, I had problems again with the issue of executing a function when pressing the ENTER key inside a ComboBox in a Windows Forms application using C #.

The first thing you think, just like in a TextBox is to use the KeyPress Event and use the same code as in it, something like:

if ((int)e.KeyChar == (int)Keys.Enter)
{
    //code here
}

But in practice, this does not work inside a ComboBox.

The Solution

As it is not the first time that I face this, on this occasion, I wanted to try to solve it in the simplest way possible, since on other occasions the truth is that I read a lot. But I got the solution.

You have to overwrite the ProcessCmdKey event and check that the active control is the ComboBox you want. This, in theory, you could do with all the controls on the form.

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

As you see if the active control is checked, so that by putting there the control you want to execute a function when pressing ENTER.

Happy coding!

Find the solution here.

My blog in Spanish

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here