My Form is not registering Enter key presses

2k views Asked by At

I am writing an educational program. I have a button which I want to be "clicked" when the user presses enter. I have set the form's accept button property to true and the KeyPreview property is also set to true. I have tried creating a custom Sub to replicate AcceptButton functionality, this does not work either, the sub runs on all keys other than when the enter key is pressed.

    Private Sub TextBoxAnswer_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles TextBoxAnswer.KeyDown
        If e.KeyCode = System.Windows.Forms.Keys.Enter Then
            CheckQ()
        End If
     End Sub

I have spent the last 3 days searching for an answer and have tried everything on google I could find. I have also just tried setting the textbox MultiLine property to true and the enter key doesn't even create a new line, just to clarify I have set the Multiline property back to false now as it should be.

1

There are 1 answers

11
LeftyCoder On

The AcceptButton property should be set = to the button you want "clicked" when enter is pressed, not a boolean value. Me.AcceptButton = buttonSubmit

Did you add a handler for the form's Keydown event to go along with setting the KeyPreview property?

Private Sub form1_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles form1.KeyDown
    If e.KeyCode = System.Windows.Forms.Keys.Enter Then
        CheckQ()
        e.Handled = true
    End If
 End Sub

Your code as you have it written for the textbox keydown event should work as well. I tried it in a test app and didn't have any issues. Do you hit a breakpoint if you place it on the CheckQ() method call?

Any one of these methods should accomplish what you are trying to do.