Procedimiento para controlar mensajes de entrada de teclado en el formulario (Windows Forms para .NET)

Windows Forms permite controlar los mensajes del teclado en el nivel de formulario, antes de que los mensajes lleguen a un control. En este artículo se muestra cómo realizar esta tarea.

Importante

La documentación de la guía de escritorio para .NET 7 y .NET 6 está en proceso de elaboración.

Control de un mensaje del teclado

Controle el evento KeyPress o KeyDown del formulario activo y establezca la propiedad KeyPreview del formulario en true. Esta propiedad hace que el formulario reciba el teclado antes de llegar a los controles del formulario. Para controlar el evento KeyPress, el siguiente código de ejemplo detecta todas las teclas numéricas y consume 1, 4 y 7.

// Detect all numeric characters at the form level and consume 1,4, and 7.
// Form.KeyPreview must be set to true for this event handler to be called.
void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar >= 48 && e.KeyChar <= 57)
    {
        MessageBox.Show($"Form.KeyPress: '{e.KeyChar}' pressed.");

        switch (e.KeyChar)
        {
            case (char)49:
            case (char)52:
            case (char)55:
                MessageBox.Show($"Form.KeyPress: '{e.KeyChar}' consumed.");
                e.Handled = true;
                break;
        }
    }
}
' Detect all numeric characters at the form level and consume 1,4, and 7.
' Form.KeyPreview must be set to true for this event handler to be called.
Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs)
    If e.KeyChar >= Chr(48) And e.KeyChar <= Chr(57) Then
        MessageBox.Show($"Form.KeyPress: '{e.KeyChar}' pressed.")

        Select Case e.KeyChar
            Case Chr(49), Chr(52), Chr(55)
                MessageBox.Show($"Form.KeyPress: '{e.KeyChar}' consumed.")
                e.Handled = True
        End Select
    End If

End Sub

Vea también