willymartin
willymartin

Reputation: 3

key down for ctrl + W wil trigger with ctrl + shift + W winForms

I want to catch the keydown event so when I press CTRL + W it will close the form. Currently My Code:

Private Sub Main_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
    If e.Control AndAlso e.KeyCode = Keys.W Then
        closeForm()
    End If
End Sub

The code is working fine except that when I press CTRL + whatever + W (example CTRL + SHIFT + W) it will also return true and execute the closeForm() method.

Any idea on how to prevent CTRL + whatever + W ?

Upvotes: 0

Views: 109

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54457

Use the e.KeyData property:

If e.KeyData = (Keys.Control Or Keys.W) Then

That will exclude all combinations other than Ctrl+W. If you wanted to do it more like what you have already then it would be:

If e.Control AndAlso Not e.Shift AndAlso Not e.Alt AndAlso e.KeyCode = Keys.W Then

As you can see, using e.KeyData is much cleaner when looking for one specific key combination.

Upvotes: 1

Related Questions