I am trying to make my program press a button in the form if the "enter" key is pressed while in a specific text box.
I have used similar code to change focus between text boxes, and it works perfectly fine.
Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
TextBox2.Focus()
End If
End Sub
In this instance, the Windows noise does not play, and the focus is changed from TextBox1 to TextBox2.
However, I tried to implement the same code while only changing one line.
Private Sub TextBox2_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox2.KeyDown
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
Button2.PerformClick()
End If
End Sub
The "e.SuppressKeyPress = True" does not stop the Windows noise from playing.
I have researched this for about three hours now, and have come up empty handed multiple times. I have tried setting the button to the default "AcceptButton", but then when I press enter in ANY text box, then the button is pressed. I only want the button to be pressed if enter is pressed in TextBox2.
I should also mention, simply pressing the button does not make the noise. Only if the user presses "enter" in TextBox2.
EDIT 1 - I have tried to debug as best I can, and it appears to only be happening when the user presses enter.
Private Sub TextBox2_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox2.KeyDown
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
End If
End Sub
Removing the button click from the code (see above) makes the Windows noise stop. I'm completely at a loss here...
e.Handled
toTrue
? – jmcilhinneySelect
rather thanFocus
. Sometimes it makes no difference but other times it does. If you callSelect
then you don't have to know which are which. – jmcilhinneyPerformClick
. Instead, refactor the code that occurs in the button click handler out into a separate method and then call that method from both the button click handler and from theTextBox2.KeyDown
method. – Chris Dunaway