How do I capture the enter key in a windows forms combobox
Solution 1
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.
Solution 2
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.
Solution 3
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.");
}
}
Solution 4
private void comboBox1_KeyDown( object sender, EventArgs e )
{
if( e.KeyCode == Keys.Enter )
{
// Do something here...
} else Application.DoEvents();
}
Solution 5
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);
}
user1576301
Updated on March 19, 2020Comments
-
user1576301 about 4 years
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 and overridden ProcessDialogKey, but nothing seems to work.
Any ideas?
/P
-
user1576301 almost 15 yearsI've already tried it. It does not work. Try it your self and see. Thats why I posted the question.
-
Warpspace almost 15 yearsOne possible reason would be that some other event handler catches the enter first and stops the rest of the handlers do their job. For example a Menu or the form itself.
-
user1576301 almost 15 yearsYou are right. ...it does work when I isolated the code to make it "postable", so the error must lie somewhere else. I'll try searching with Petros hint. Thanks guys.
-
Phil Lambert over 9 yearsif (e.KeyChar == (char)Keys.Enter) { }
-
Shereef Marzouk about 7 yearsthere is a property on the form that is called KeyPreview, enable it i guess