toolStripTextBox action when Enter is pressed

M

matthewr

In Internet Explorer, for example, when you hit return in the address
bar, the Go button is pressed. In my program, I have a toolstrip with a
textbox and button. How do I ensure the button is 'clicked' when Enter
is pressed in the text box.

I can't set the form's AcceptButton property to the toolStripButton -
it doesn't allow toolStripButtons to be set as the AcceptButton.

As a last resort, I could create a keypress event handler for the
textbox that called button_click() if return was pressed but that's not
a great solution.

TIA
 
G

Guest

matthewr said:
In Internet Explorer, for example, when you hit return in the address
bar, the Go button is pressed. In my program, I have a toolstrip with a
textbox and button. How do I ensure the button is 'clicked' when Enter
is pressed in the text box.

I can't set the form's AcceptButton property to the toolStripButton -
it doesn't allow toolStripButtons to be set as the AcceptButton.

Set the Form's KeyPreview property to true, handle the Form's KeyPress
property, then in the KeyPress handler, check if your textbox is focused and
the Enter key was pressed. If so, tell the Go button to PerformClick and
handle the keypress.

private void Form1_KeyPress(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
// if textbox is focused and Enter key was pressed
if (this.textBox1.Focused && e.KeyChar == '\r')
{
// click the Go button
this.button1.PerformClick();
// don't allow the Enter key to pass to textbox
e.Handled = true;
}
}
 
M

matthewr

Thanks, Timm. I was hoping to avoid keypress handling and find a way to
use a toolStripButton as the form's AcceptButton, but it doesn't look
like that's possible/easy.
 

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