I have a few TextBox on the WinForm. I would like the focus to move to the next control when Enter key is pressed? Whenever a textbox gains control, it will also select the text, so that any editing will replace the current one.
What is the best way to do this?
Tab as Enter: create a user control which inherits textbox, override the KeyPress
method. If the user presses enter you can either call SendKeys.Send("{TAB}")
or System.Windows.Forms.Control.SelectNextControl()
. Note you can achieve the same using the KeyPress
event.
Focus Entire text: Again, via override or events, target the GotFocus
event and then call TextBox.Select
method.
A couple of code examples in C# using SelectNextControl.
The first moves to the next control when ENTER is pressed.
private void Control_KeyUp( object sender, KeyEventArgs e )
{
if( (e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return) )
{
this.SelectNextControl( (Control)sender, true, true, true, true );
}
}
The second uses the UP and DOWN arrows to move through the controls.
private void Control_KeyUp( object sender, KeyEventArgs e )
{
if( e.KeyCode == Keys.Up )
{
this.SelectNextControl( (Control)sender, false, true, true, true );
}
else if( e.KeyCode == Keys.Down )
{
this.SelectNextControl( (Control)sender, true, true, true, true );
}
}
See MSDN SelectNextControl Method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With