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 🙂

Enter Instead of Tab

17 Responses

  1. 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

    Mark Christian Aguilar-Barra December 15, 2004 at 8:29 am #
  2. yes, then just simply add : SendKeys.Send(“{TAB}”)

    trac December 23, 2004 at 6:36 am #
  3. hello
    i have problem with DataGrid ,when tablestyle added to it ,Enter processing not work.
    please help me.

    hany bonyadi December 29, 2004 at 12:56 pm #
  4. Sorry for my English….

    How set BEEP=OFF When I Press “Enter”. And I Do Me.ProcessTabKey(Not e.Shift)

    Savager December 30, 2004 at 6:25 am #
  5. 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

    nana osei December 30, 2004 at 1:31 am #
  6. I want to know how to create autofilling combo boxes by using vb code.

    Sajith Poduval January 2, 2005 at 10:24 am #
  7. 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???)

    Chris Bentley January 9, 2005 at 2:21 pm #
  8. The e.Handled = True statement should suppress the beep.

    Bud Staniek January 9, 2005 at 4:02 pm #
  9. >>> 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

    Chris Bentley January 10, 2005 at 5:21 am #
  10. j3204-9324-0

    3884273 January 11, 2005 at 6:58 am #
  11. [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).

    TJ Neal January 14, 2005 at 9:04 pm #
  12. sss

    harmeet singh January 15, 2005 at 4:18 pm #
  13. 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();
    }
    }

    Mitra March 1, 2005 at 1:16 am #
  14. 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.

    sultan mcdoom March 8, 2005 at 7:55 pm #
  15. 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

    Matthew September 10, 2005 at 12:06 am #
  16. e.Handler = True works for everything but DatePicker Controls.

    What works for DatePickers?

    Corri April 12, 2006 at 6:00 pm #
  17. 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

    parvita July 12, 2006 at 9:33 am #

Leave a Reply