Control.PreviewKeyDown Evento

Definición

Se produce antes que el evento KeyDown cuando se presiona una tecla mientras el foco está en este control.Occurs before the KeyDown event when a key is pressed while focus is on this control.

public:
 event System::Windows::Forms::PreviewKeyDownEventHandler ^ PreviewKeyDown;
public event System.Windows.Forms.PreviewKeyDownEventHandler PreviewKeyDown;
member this.PreviewKeyDown : System.Windows.Forms.PreviewKeyDownEventHandler 
Public Custom Event PreviewKeyDown As PreviewKeyDownEventHandler 

Ejemplos

En el ejemplo de código siguiente se muestra un Button que incluye un ContextMenuStrip.The following code example demonstrates a Button that includes a ContextMenuStrip. Cuando el Button tiene el foco y presiona las teclas flecha arriba o flecha abajo, aparece el ContextMenuStrip.When the Button has the focus and you press the UP ARROW or DOWN ARROW keys, the ContextMenuStrip appears. El controlador de eventos PreviewKeyDown detecta cuándo se presionan las teclas flecha arriba o flecha abajo y establece la propiedad IsInputKey en true.The PreviewKeyDown event handler detects when the UP ARROW or DOWN ARROW keys are pressed and sets the IsInputKey property to true. Esto provoca el evento KeyDown para que pueda mostrar el ContextMenuStrip.This raises the KeyDown event so that you can display the ContextMenuStrip. No debe colocar ninguna lógica en el controlador de eventos PreviewKeyDown, excepto para establecer la propiedad IsInputKey.You should not put any logic in the PreviewKeyDown event handler, other than to set the IsInputKey property. En su lugar, debe colocar la lógica en el controlador de eventos KeyDown.Instead, you should put your logic in the KeyDown event handler.

public Form1()
{
    InitializeComponent();

    // Form that has a button on it
    button1.PreviewKeyDown +=new PreviewKeyDownEventHandler(button1_PreviewKeyDown);
    button1.KeyDown += new KeyEventHandler(button1_KeyDown);
    button1.ContextMenuStrip = new ContextMenuStrip();
    // Add items to ContextMenuStrip
    button1.ContextMenuStrip.Items.Add("One");
    button1.ContextMenuStrip.Items.Add("Two");
    button1.ContextMenuStrip.Items.Add("Three");
}

// By default, KeyDown does not fire for the ARROW keys
void button1_KeyDown(object sender, KeyEventArgs e)
{
    switch (e.KeyCode)
    {
        case Keys.Down:
        case Keys.Up:
            if (button1.ContextMenuStrip != null)
            {
                button1.ContextMenuStrip.Show(button1,
                    new Point(0, button1.Height), ToolStripDropDownDirection.BelowRight);
            }
            break;
    }
}

// PreviewKeyDown is where you preview the key.
// Do not put any logic here, instead use the
// KeyDown event after setting IsInputKey to true.
private void button1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    switch (e.KeyCode)
    {
        case Keys.Down:
        case Keys.Up:
            e.IsInputKey = true;
            break;
    }
}
Public Class Form1

    Public Sub New()
        InitializeComponent()
        ' Form that has a button on it
        AddHandler Button1.PreviewKeyDown, AddressOf Me.button1_PreviewKeyDown
        AddHandler Button1.KeyDown, AddressOf Me.button1_KeyDown
        Button1.ContextMenuStrip = New ContextMenuStrip
        ' Add items to ContextMenuStrip
        Button1.ContextMenuStrip.Items.Add("One")
        Button1.ContextMenuStrip.Items.Add("Two")
        Button1.ContextMenuStrip.Items.Add("Three")
    End Sub

    ' By default, KeyDown does not fire for the ARROW keys
    Private Sub button1_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)
        Select Case (e.KeyCode)
            Case Keys.Down, Keys.Up
                If (Not (Button1.ContextMenuStrip) Is Nothing) Then
                    Button1.ContextMenuStrip.Show(Button1, _
                        New Point(0, Button1.Height), ToolStripDropDownDirection.BelowRight)
                End If
        End Select
    End Sub

    ' PreviewKeyDown is where you preview the key.
    ' Do not put any logic here, instead use the
    ' KeyDown event after setting IsInputKey to true.
    Private Sub button1_PreviewKeyDown(ByVal sender As Object, ByVal e As PreviewKeyDownEventArgs)
        Select Case (e.KeyCode)
            Case Keys.Down, Keys.Up
                e.IsInputKey = True
        End Select
    End Sub

End Class

Comentarios

Algunos controles omiten normalmente algunas de las pulsaciones de teclas, como TAB, Return, ESC y las teclas de dirección, ya que no se consideran presiones de tecla de entrada.Some key presses, such as the TAB, RETURN, ESC, and arrow keys, are typically ignored by some controls because they are not considered input key presses. Por ejemplo, de forma predeterminada, un control Button omite las teclas de dirección.For example, by default, a Button control ignores the arrow keys. Presionar las teclas de dirección normalmente hace que el foco se mueva al control anterior o al siguiente.Pressing the arrow keys typically causes the focus to move to the previous or next control. Las teclas de dirección se consideran claves de navegación y, normalmente, las teclas no generan el evento KeyDown para un Button.The arrow keys are considered navigation keys and pressing these keys typically do not raise the KeyDown event for a Button. Sin embargo, si se presionan las teclas de dirección para un Button, se genera el evento PreviewKeyDown.However, pressing the arrow keys for a Button does raise the PreviewKeyDown event. Al controlar el evento PreviewKeyDown para un Button y establecer la propiedad IsInputKey en true, puede generar el evento KeyDown cuando se presionan las teclas de dirección.By handling the PreviewKeyDown event for a Button and setting the IsInputKey property to true, you can raise the KeyDown event when the arrow keys are pressed. Sin embargo, si controla las teclas de dirección, el foco ya no pasará al control anterior o al siguiente.However, if you handle the arrow keys, the focus will no longer move to the previous or next control.

Para obtener más información sobre el manejo de eventos, consulte controlar y provocar eventos.For more information about handling events, see Handling and Raising Events.

Se aplica a