Click here to Skip to main content
15,886,518 members
Articles / Desktop Programming / Windows Forms
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
4.00/5 (3 votes)
25 Jul 2017CPOL 9.2K   5  
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:

C#
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.

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer DrUalcman
Philippines Philippines
I am a programmer with skill in c#, VB, MVC, .NET CORE, JAVASCRPT, HTML, ASP, CSS, windows forms, windows app.

I like help the dev community with my experiencies, and sharing my code to everybody.

Comments and Discussions

 
-- There are no messages in this forum --