Saturn
Saturn

Reputation: 18149

Form keyDown not working?

Private Sub Form1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
    If e.Control Then
        MessageBox.Show("aaaa")
    End If
End Sub

As you can see, my form will check for when the control key is pressed down. But it doesn't work. Why?

Upvotes: 8

Views: 20596

Answers (3)

Balibrera
Balibrera

Reputation: 185

You need to set KeyPreview to true when loading the form, it should work then

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    Me.KeyPreview = True
End Sub

Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
    MsgBox(e.KeyChar)
End Sub

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 941317

That works fine. I assume you have other controls in your form. One of them will get the focus, never the form. Keyboard input only goes to the control with the focus.

You can set the form's KeyPreview property to True. The Winforms' way is to override the ProcessCmdKey() method.

Upvotes: 1

wageoghe
wageoghe

Reputation: 27608

I am not near a computer now so I can't test this, but when I have wanted to get key events on a form before, I would set Form1.KeyPreview to True (or something similar).

Upvotes: 23

Related Questions