Mech_Engineer
Mech_Engineer

Reputation: 555

Catch if user presses enter key in textbox

I'm trying to catch in a Event if the user presses the enter key. If followed these instructions found on the MSDN documentation pages.

This is my Event code for the Textbox:

Private Sub tbOccurrenceElevation_KeyDown(sender As Object, e As KeyEventArgs) Handles tbOccurrenceElevation.KeyDown

    ' Check if the enter key is pressed
    If e.KeyCode = Keys.Return Then
        OccurrenceElevation_Changed()
    End If

End Sub

My problem is: when I push any button on the keyboard the Event is triggered, but when I press the enter ( return ) key nothing happens?

I tried changing the Textbox property to AcceptsReturn = True but no luck.

Extra info: The textbox is located on a UserControl and not a form control.

Upvotes: 0

Views: 5939

Answers (2)

3vts
3vts

Reputation: 828

Try this:

Private Sub tbOccurrenceElevation_KeyDown(sender As Object, e As KeyEventArgs) Handles tbOccurrenceElevation.KeyDown

    ' Check if the enter key is pressed
    If e.KeyCode = Keys.Enter or e.KeyCode = Keys.Return Then
        OccurrenceElevation_Changed()
    End If

End Sub

You have to remember most of the keyboards have both Enter and Return. The code for those is different so you have to include them both

Upvotes: 0

Visual Vincent
Visual Vincent

Reputation: 18330

If something else is stopping the text box from receiving the enter key you could try overriding ProcessCmdKey of the UserControl instead.

It might work, but it all depends on where in the event chain that the parent intercepts the message.

Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, keyData As System.Windows.Forms.Keys) As Boolean
    If keyData = Keys.Return AndAlso tbOccurrenceElevation.Focused = True Then
        'Do your stuff here.
        Return True 'We've handled the key press.
    End If
    Return MyBase.ProcessCmdKey(msg, keyData)
End Function

Upvotes: 1

Related Questions