Intercepting the Enter key

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
 
U

Uchiha Jax

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
}
}
}
 
S

Steve Murphy

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
 
U

Uchiha Jax

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?
 
S

Steve Murphy

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
 
S

sadhu

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
 
S

Steve Murphy

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top