How do I stop a button from triggering when the enter key is pressed? (focused)

1.4k views Asked by At

(I would say hello here, but Stackoverflow always removes it for some reason)
My problem is that on my Visual Basic form the button that I use to close the form can be triggered by the enter key. This is a problem because my form opens a webpage that frequently uses forms, meaning that the enter key on a form will close the window!

Therefore, I need to find a way of stopping the focus on this button. It is a custom-ish button and is its own class but inherits from a normal button. Here's some diagrams:

Stage 1: Before the user focuses on the WebKitBrowser

Stage 1: Before the user focuses on the WebKitBrowser

Stage 2: After the user focuses on the WebKitBrowser

Stage 2: After the user focuses on the WebKitBrowser

As you can see, the button is "focused" with a white border, similar to a normal Windows button where the border is instead blue. If I was to press enter at this stage, the form would close.

In conclusion, or TL;DR, how do I stop my close button from being focused?

1

There are 1 answers

0
Amen Jlili On BEST ANSWER

Your button by default is included in the tab order which results in the focus effect.

Try removing the button from the tab order. You can do by setting the TabStop of your button to False when your form loads. I tried the example below and it worked for me.

Before

Code:

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Me.Close()
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    End Sub
End Class

enter image description here

After

Code:

Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Me.Close()
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Button1.TabStop = False
End Sub

End Class

enter image description here