65.9K
CodeProject is changing. Read more.
Home

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

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (3 votes)

Jul 26, 2017

CPOL
viewsIcon

9581

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