Search code examples
vb.netvisual-studio-2010keypress

How do I check whether a key was pressed and then do something with the value?


I wanted to check if a key was pressed in a form, then perform a subroutine with that key. The code below works only if there are no other controls in the form. What should I do?

Private Sub MainForm_KeyPress1(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
    MsgBox(e.KeyChar)
End Sub

Solution

  • You can set the KeyPreview property of your form to True. This way, you'll catch all the KeyPress events on your form (which will be afterwards handled by the control the keypress happened on, if you didn't set the Handled property of the KeyPressEventArgs to True).

    When this property is set to true, the form will receive all KeyPress, KeyDown, and KeyUp events. After the form's event handlers have completed processing the keystroke, the keystroke is then assigned to the control with focus. For example, if the KeyPreview property is set to true and the currently selected control is a TextBox, after the keystroke is handled by the event handlers of the form the TextBox control will receive the key that was pressed. To handle keyboard events only at the form level and not allow controls to receive keyboard events, set the KeyPressEventArgs.Handled property in your form's KeyPress event handler to true.

    Source: MSDN