Aaron York
Aaron York

Reputation: 37

If event on specific Keypress

I have a very simple -albeit frustrating- question today. I need to have an If statement that runs code only if the user has pressed a certain key. How do I do that? I have the Keypress sub already made:

    Private Sub PictureBox1_KeyPress(sender As Object, e As EventArgs) Handles ClickField1.KeyPress
         If KeyPressed = Z Then
              'Run Code
         Else
               Return
         End If

What's the 'If KeyPressed = Z Then' proper syntax? Thanks in advance!

Upvotes: 0

Views: 95

Answers (2)

Blackwood
Blackwood

Reputation: 4534

The e parameter of the KeyPress event handler should be a KeyPressEventArgs object and not an EventArgs object. KeyPressEventArgs has a KeyChar property that contains the Char value that represents the key that was pressed.

If you want to check for uppercase "Z", you can use this code:

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
    If e.KeyChar = "Z"c Then
        'run code
    Else
        Return
    End If
End Sub

Upvotes: 1

CruleD
CruleD

Reputation: 1183

There are multiple ways, here's something for a start.

 If e.KeyChar.ToString.ToLower.Equals("z") Then 'Both z and Z
            'Something
 End If

Upvotes: 1

Related Questions