Intercepting the Enter key

  • Thread starter Thread starter Steve Murphy
  • Start date Start date
S

Steve Murphy

I have a default button on a form, but when a certain textbox has focus, I want
to intercept Enter key events and perform a different action. Is there an easy
way to do this, or should I just check the textbox's focus in the default
button's event handler?

Thanks in advance,
Steve Murphy
 
You could use the KeyUp or KeyDown event handler on the textbox and check
the KeyEventArgs.KeyCode property agains the Keys enumerable Keys.Enter. e.g

public class Form1:System.Windows.Forms.Form
{
private TextBox textBox1
public Form1
{
/// add button and textbox to form etc

textBox1.KeyUp += new KeyEventHandler(TextBox1_KeyUp);
}

private void TextBox1_KeyUp(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter)
{
RunSomeMethod(); /// the method you wish to run
}
}
}
 
Uchiha Jax said:
You could use the KeyUp or KeyDown event handler on the textbox and check
the KeyEventArgs.KeyCode property agains the Keys enumerable Keys.Enter. e.g

Thanks. This works only in the KeyUp event. Do you have any thoughts on why? Not
that it's important; I'm just curious.

Also, however, this does not filter the event, and the default button event
still runs.

Thanks,
Steve Murphy
 
Oh yes sorry, far easier is to put in the button eventhandler

if(!this.textBox1.Focused)
{
RunYourRoutine();
}
else
{
//// do something else
}

Although if you have lots of these types of textbox you may want to consider
a different solution, is this ASP.NET?
 
Oh yes sorry, far easier is to put in the button eventhandler

No problem. I was just wondering if there was a better way.

Thanks again,
Steve Murphy
 
That's because the AcceptEnter property of the textbox is set to false.
If you set it to true, you'll get event notification for KeyDown also.
You'll be able to filter it too.

Regards
Senthil
 
sadhu said:
That's because the AcceptEnter property of the textbox is set to false.
If you set it to true, you'll get event notification for KeyDown also.
You'll be able to filter it too.

Nope. Tried that. It's okay, putting the code in the button method is not a
problem.

Thanks,
Steve Murphy
 
Back
Top