Search code examples
vb.netkeypress

e.KeyCode Doesn't want to work for me


So I am trying to write some simple code that toggles something on or off when the key "g" is pressed. I'll let you take a look at the code and hopefully it is something staring me in the face...

    Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs)
    If e.KeyCode = Keys.G Then
        If Label2.Text = "Off" Then
            Label2.Text = "On"
            Label2.ForeColor = Color.Green
        Else
            Label2.Text = "Off"
            Label2.ForeColor = Color.Red
        End If
    End If
End Sub

Solution

  • You have somehow lost the "Handes Me.KeyDown" on the end your handler...note the end of the first line:

    Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
        If e.KeyCode = Keys.G Then
            If Label2.Text = "Off" Then
                Label2.Text = "On"
                Label2.ForeColor = Color.Green
            Else
                Label2.Text = "Off"
                Label2.ForeColor = Color.Red
            End If
        End If
    End Sub
    

    Also, make sure you've got the KeyPreview property of your Form set to True.