Reputation: 1338
I am creating a winforms application and I am simply trying to use a button to allow the user to submit the form. I have the following code for the button
With duplicate_button
.Parent = action_box
.TabIndex = 4
.Width = 125
.Top = 25
.Left = (.Parent.Width / 2) - (.Width / 2)
AddHandler .KeyDown, AddressOf duplicate
End With
Private Sub duplicate(sender As Object, e As KeyEventArgs)
Console.Write(e.KeyCode)
End Sub
However, the duplicate function does not get called when the user presses the enter key. It does get called for any other key on the keyboard, just not the enter key. But I really only need it to work for the enter key.
I already tried setting the previewkeys to true and setting the acceptbutton on the form to this button, but neither of them changed anything.
I also tried using the keypress event, but again the enter key is not detected.
Upvotes: 0
Views: 5024
Reputation: 32248
When a Button has the Focus, pressing the ENTER key will raise the Click
and KeyUp
events.
The TAB Key will raise the KeyUp event, if pressing that Key will cause the Focus to reach the Button, but not if it's pressed to move the Focus to another control.
If Shift+TAB are pressed to move the Focus to the Button
, the KeyUp
event is raised twice.
The KeyDown
event is raised only when pressing the Shift+TAB keys to move the Focus to the previous control in the TabIndex
order.
Any other key pressed while the Button has the Focus, will raise the KeyUp
and KeyDown
events.
The KeyPreview
property of the Form will not change this behavior.
With the exception of the Shift+TAB keys, when used to move the Focus to the previous control.
In this case, only the KeyDown
event is raised.
If the Button is the AcceptButton or the CancelButton of a Form, pressing the ENTER or ESC keys will raise the Click
event of the Button.
This could cause a problem if multiline TextBox
controls are also present, because pressing the ENTER key will not generate a new line, since the KeyDown
event is not raised for this Key, only KeyUp
.
Upvotes: 3