Duncan Mackenzie (gravatar)

Enter Instead of Tab

I received another interesting, and common, question today about using Enter instead of (or in addition to) the Tab key to move the focus between fields on a form. Well, that isn't too hard to accomplish, but it can get tricky once you consider all the different situations...

First, the easy... set your Form's KeyPreview property to true, override OnKeyUp (or OnKeyDown... can't think of any real reason to use one or the other in this case), check for the Enter key, then call your Form's ProcessTabKey method.

    Protected Overrides Sub OnKeyUp(ByVal e As System.Windows.Forms.KeyEventArgs)
        If e.KeyCode = Keys.Enter Then
            e.Handled = True
            Me.ProcessTabKey(Not e.Shift)
        Else
            e.Handled = False
            MyBase.OnKeyUp(e)
        End If
    End Sub

Now... what is wrong with that code?

In the simple case, nothing... but I found a couple of issues with it.

  • If you have the AcceptButton property of your Form set, which means you have a default button on the Form, then your code will never get called... the key event is handled at some point farther up the chain
  • If you have multiline textboxes on your Form, the enter key will not work within them ... which means your users will not be able to create any new lines in those textboxes.

The first issue is easiest to solve if you just decide not to have a default button set on your form, because any other solution (such as overriding ProcessDialogKey) will stop the default button behaviour so that the enter key can be used for moving focus.

The second problem is not too difficult to handle, you can modify your code to check for certain properties of the TextBox control, but this may not work for other controls that also wish to accept the Enter key as input.

        If e.KeyCode = Keys.Enter Then
            If TypeOf Me.ActiveControl Is TextBox Then
                Dim tb As TextBox = DirectCast(Me.ActiveControl, TextBox)
                If tb.Multiline AndAlso tb.AcceptsReturn Then
                    e.Handled = False
                    MyBase.OnKeyUp(e)
                    Exit Sub
                End If
            End If
            e.Handled = True
            Me.ProcessTabKey(Not e.Shift)
        Else
            e.Handled = False
            MyBase.OnKeyUp(e)
        End If

Oh, and there was another part to the original question... what if I want to respond to the Enter key to do some processing on the value that was just entered. Well, for that result either with or without the 'enter instead of tab' code, you would just choose to handle the KeyDown event for the control in question.

    Private Sub TextBox2_KeyDown(ByVal sender As Object, _
            ByVal e As System.Windows.Forms.KeyEventArgs) _
            Handles TextBox2.KeyDown
        If e.KeyCode = Keys.Enter Then
            MsgBox("do something!")
        End If
    End Sub

Of course, after your code 'does something', the focus will also move to the next control... both sets of code, the Form's OnKeyUp routine and the control's KeyDown event handler, execute when the user hits Enter on this particular control.

I've gotten flack in the past for articles that discuss 'simple' topics, but I hope this is useful to some of the folks that find it :)

17 Comments

  • Mark Christian Aguilar-Barra (gravatar)

    Mark Christian Aguilar-Barra said
    December 14, 2004

    id like to ask if there's a property of the textbox that will restrict the user from inputting letters or numbers? just like in macromedia flash. Im a computer science student from the Philippines. Thank you. here's my email add.= markchristian_aguilar@yahoo.com

  • yes, then just simply add : SendKeys.Send("{TAB}")

  • hello i have problem with DataGrid ,when tablestyle added to it ,Enter processing not work. please help me.

  • id like to ask if there's a property of the textbox that will restrict the user from inputting letters or numbers? just like in macromedia flash. Im a computer science student from ghana email: nanafrifa@yahoo.co.uk

  • Savager (gravatar)

    Savager said
    December 29, 2004

    Sorry for my English.... How set BEEP=OFF When I Press "Enter". And I Do Me.ProcessTabKey(Not e.Shift)

  • I want to know how to create autofilling combo boxes by using vb code.

  • I've got the same problem with one of the 'system' sounds occuring when 'Enter' is hit. If I handle the Enter key in OnKeyUp then the beep seems to occur before I enter the event handler. I changed to handling the Enter key within OnKeyDown and there is no beep during the handler - ergo the beep must be occuring within "KeyPressed" I'm tempted to handle KeyPressed as well and just set "handled" to true for Enter, but, I don't think that Enter actually raises a KeyPressed (or did I read the docs incorrectly???)

  • Bud Staniek (gravatar)

    Bud Staniek said
    January 09, 2005

    The e.Handled = True statement should suppress the beep.

  • >>> The e.Handled = True statement should suppress the beep. "Should" being the operative word... She's still beeping at me - to the extent that I think I'll turn of the sound programatically and restore it when *I* think it should be on. To make matters worse, when I convert the enter to a tab for a DateTimePicker control I get a different beep - actually it's Windows XP Ding

  • j3204-9324-0

  • TJ Neal (gravatar)

    TJ Neal said
    January 14, 2005

    [code] Private Sub frmFirst_Report_KeyPress _ (ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) _ Handles MyBase.KeyPress If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Enter) Then If TypeOf Me.ActiveControl Is TextBox Then Dim tb As TextBox = DirectCast(Me.ActiveControl, TextBox) If tb.Multiline AndAlso tb.AcceptsReturn Then e.Handled = False Exit Sub End If End If e.Handled = True Dim oform As Form = Me.FindForm oform.SelectNextControl(oform.ActiveControl, True, True, True, True) oform.ActiveControl.Focus() End If End Sub [/code] Set your form to KeyPreview and place this routine on the form. You will not get a beep at all and you do not need to access any overrides. (If you prefer SendKey.Send("{TAB}") instead of the SelectNextControl it will function also).

  • harmeet singh (gravatar)

    harmeet singh said
    January 15, 2005

    sss

  • Mitra (gravatar)

    Mitra said
    February 28, 2005

    I looked around and this is the best I came up with in (C# - Application). I had a username and password field box and i wanted the focus to change on ENTER and not TAB. You have to use this for the KeyDown Event handler private void textBoxUserName_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { if ( e.KeyCode == Keys.Enter ) { this.GetNextControl( this.textBoxUserName, true ).Focus(); } }

  • sultan mcdoom (gravatar)

    sultan mcdoom said
    March 08, 2005

    this came from another site and is a much simpler solution Private Sub Form_KeyPress(KeyAscii As Integer) If KeyAscii = vbKeyReturn Then KeyAscii = 0 SendKeys "{TAB}" End If End Sub And we all know that by using the KeyAscii = 0 keeps your computer from beeping when you use the Enter key as a Tab. Now the above code works with about 90% of all the controls, however there are some controls where it just does not work, such as the DatePicker control for one.

  • Matthew (gravatar)

    Matthew said
    September 09, 2005

    The trick is to set e.Handled = true before you do anything else !!! Private Sub txtSearchValue_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtSearchValue.KeyPress If sysEnterEqualsTab = True Then If e.KeyChar = Microsoft.VisualBasic.ChrW(13) Then e.Handled = True Me.ActiveControl = Me.GetNextControl(txtSearchValue, True) End If End If End Sub

  • Corri (gravatar)

    Corri said
    April 12, 2006

    e.Handler = True works for everything but DatePicker Controls. What works for DatePickers?

  • help me actually on run time textbox is dishabled using textbox.enabled=false but there is change in color of textbox e.g. white to gray this is possible with e.handled= true on key press event but i want that this dishabling accure with a particular condition or say with in if-else statement plz can u mail me or give solution of this problem with coding i am waiting ur reply thanks

Your Information
Mrs. Gravatar (gravatar)

<-- It's a gravatar

your comment