Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Press Enter to move to next control

Tags:

c#

winforms

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?

like image 319
david.healed Avatar asked Jul 06 '09 16:07

david.healed


2 Answers

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.

like image 165
ng5000 Avatar answered Oct 21 '22 05:10

ng5000


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

like image 23
jim31415 Avatar answered Oct 21 '22 06:10

jim31415