Question

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
Was it helpful?

Solution

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%.

OTHER TIPS

If you want to go right to the heart of the key events, and intercept even the arrows and other focus-changing keys, you'll need something like this:

Protected Overrides Function ProcessDialogKey(ByVal keyData As System.Windows.Forms.Keys) As Boolean
        Select Case keyData
            Case Keys.Enter
                'your logic here
                Return True  'this surpresses any default action
        End Select
        Return MyBase.ProcessDialogKey(keyData) 'this allows the default action to be processed for any cases you haven't explicitly intercepted

    End Function
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top