[ACCEPTED]-How do I capture the enter key in a windows forms combobox-combobox
Hook up the KeyPress event to a method like 3 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 2 with VS2008 and it works.
If it isn't working 1 for you, please post your code.
In case you define AcceptButton on your 6 form, you cannot listen to Enter key in 5 KeyDown/KeyUp/KeyPress.
In order to check 4 for that, you need to override ProcessCmdKey 3 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 2 you message box if you are on combo box 1 and it works as before for all other controls.
or altertatively you can hook up the KeyDown 1 event:
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("Enter pressed.");
}
}
private void comboBox1_KeyDown( object sender, EventArgs e )
{
if( e.KeyCode == Keys.Enter )
{
// Do something here...
} else Application.DoEvents();
}
0
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);
}
0
It could be that your dialog has a button 11 that's eating the enter key because it's 10 set to be the AcceptButton in the form property.
If 9 that's the case then you solve this like 8 this by unsetting the AcceptButton property 7 when the control gets focus then resetting 6 it back once the control loses focus ( in 5 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 4 have to admit not liking my own solution 3 as it seems a little hacky to unset/set 2 the AcceptButton property so if anyone has 1 a better solution then I'd be interested
protected void Form_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13) // or Key.Enter or Key.Return
{
MessageBox.Show("Enter pressed", "KeyPress Event");
}
}
Don't forget to set KeyPreview to true on 1 the form.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.