Search code examples
vb.netwinformsbuttonbackcolor

Changing backColor of button when pressed Enter in keyboard


 Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
        If e.KeyCode = Keys.Enter Then
            Button1.BackColor = Color.Aqua
        End If
    End Sub

I want to change the BackColor of the button if enter key is pressed but it does nothing when I pressed the enter key. Form KeyPreview is set to true.If Enter key is replaced by another key the code is executed


Solution

  • You can override ProcessCmdKey like this:

    Public Class Form1
    
        Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
            If keyData = Keys.Enter Then
                Button1.BackColor = Color.Aqua
            End If
            Return MyBase.ProcessCmdKey(msg, keyData)
        End Function
    
    End Class