I'm working with a WinForm app in C#, after I type something in a textbox I want to hit the Enter key but the textbox still has focus (flashing cursor is still in textbox), how can I achieve this?
Thanks
I'm working with a WinForm app in C#, after I type something in a textbox I want to hit the Enter key but the textbox still has focus (flashing cursor is still in textbox), how can I achieve this?
Thanks
The simple option is just to set the forms's AcceptButton to the button you want pressed (usually "OK" etc):
TextBox tb = new TextBox();
Button btn = new Button { Dock = DockStyle.Bottom };
btn.Click += delegate { Debug.WriteLine("Submit: " + tb.Text); };
Application.Run(new Form { AcceptButton = btn, Controls = { tb, btn } });
If this isn't an option, you can look at the KeyDown event etc, but that is more work...
TextBox tb = new TextBox();
Button btn = new Button { Dock = DockStyle.Bottom };
btn.Click += delegate { Debug.WriteLine("Submit: " + tb.Text); };
tb.KeyDown += (sender,args) => {
if (args.KeyCode == Keys.Return)
{
btn.PerformClick();
}
};
Application.Run(new Form { Controls = { tb, btn } });
Setting the forms's AcceptButton to the button I need worked great!
Thanks Marc
The usual way to do this is to set the Form
's AcceptButton
to the button you want "clicked". You can do this either in the VS designer or in code and the AcceptButton
can be changed at any time.
This may or may not be applicable to your situation, but I have used this in conjunction with GotFocus
events for different TextBox
es on my form to enable different behavior based on where the user hit Enter. For example:
void TextBox1_GotFocus(object sender, EventArgs e)
{
this.AcceptButton = ProcessTextBox1;
}
void TextBox2_GotFocus(object sender, EventArgs e)
{
this.AcceptButton = ProcessTextBox2;
}
One thing to be careful of when using this method is that you don't leave the AcceptButton
set to ProcessTextBox1
when TextBox3
becomes focused. I would recommend using either the LostFocus
event on the TextBox
es that set the AcceptButton
, or create a GotFocus
method that all of the controls that don't use a specific AcceptButton
call.
YOu can trap it on the keyup event http://www.itjungles.com/dotnet/c-how-to-easily-detect-enter-key-in-textbox-and-execute-a-method