Vb.net – How to prevent the enter key from triggering a click event when a button is in focus

enterkeycodevb.netvisual studio 2012

I'm trying to make a program which can accept button based inputs as well as keyboard based inputs which it then outputs to a text box. However I would like to use the Enter key to trigger the function to output to the text box. However since there are buttons on the form. They will be triggered like a mouse click event when the enter key is pressed. I need to find a way to either make the enter key only trigger the event I want and not to trigger the button. Or I need to find a way to make the buttons never have focus and for the focus always to be on the form itself while still having the buttons be clickable. Any help?

       If e.KeyCode = Keys.Enter Then
        SecondNum = Val(TB_Output.Text)
        ResultEquals()
        TB_Output.Text = Result
    End If

Best Answer

Theoretically, setting KeyPreview property of the form to True should do it. Then handle KeyDown event, and make sure to set e.Handled to True on pressing the Enter key (or e.SuppressKeyPress, depends on implementation of controls you are working with).

I tried this approach in a sample project just now, however, and it did not work with a button for some reason. You may need to resort to using WndProc on the form level, this always works 100%.

Related Topic