Leer en inglés

Compartir a través de


Form.KeyPreview Propiedad

Definición

Obtiene o establece un valor que indica si el formulario recibe los eventos clave antes de que pasen al control que tiene el foco.

public bool KeyPreview { get; set; }

Valor de propiedad

true si el formulario recibe todos los eventos clave; es false si el control seleccionado actualmente en el formulario recibe eventos clave. De manera predeterminada, es false.

Ejemplos

En el ejemplo siguiente se muestra cómo establecer la propiedad de KeyPreview un formulario en true y controlar los eventos clave en el nivel de formulario. Para ejecutar el ejemplo, pegue el código siguiente en un formulario en blanco.

using System.Windows.Forms;

public class Form1 :
    System.Windows.Forms.Form

// Declare the controls contained on the form.
{
    private MyMnemonicButton button1;
    internal System.Windows.Forms.ListBox ListBox1;

    public Form1() : base()
    {
        // Set KeyPreview object to true to allow the form to process 
        // the key before the control with focus processes it.
        this.KeyPreview = true;

        // Add a MyMnemonicButton.  
        button1 = new MyMnemonicButton();
        button1.Text = "&Click";
        button1.Location = new System.Drawing.Point(100, 120);
        this.Controls.Add(button1);

        // Initialize a ListBox control and the form itself.
        this.ListBox1 = new System.Windows.Forms.ListBox();
        this.SuspendLayout();
        this.ListBox1.Location = new System.Drawing.Point(8, 8);
        this.ListBox1.Name = "ListBox1";
        this.ListBox1.Size = new System.Drawing.Size(120, 95);
        this.ListBox1.TabIndex = 0;
        this.ListBox1.Text = "Press a key";
        this.ClientSize = new System.Drawing.Size(292, 266);
        this.Controls.Add(this.ListBox1);
        this.Name = "Form1";
        this.Text = "Form1";
        this.ResumeLayout(false);

        // Associate the event-handling method with the
        // KeyDown event.
        this.KeyDown += new KeyEventHandler(Form1_KeyDown);
    }

    // The form will handle all key events before the control with  
    // focus handles them.  Show the keys pressed by adding the
    // KeyCode object to ListBox1. Ensure the processing is passed
    // to the control with focus by setting the KeyEventArg.Handled
    // property to false.
    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        ListBox1.Items.Add(e.KeyCode);
        e.Handled = false;
    }

    [System.STAThreadAttribute]
    public static void Main()
    {
        Application.Run(new Form1());
    }
}

// This button is a simple extension of the button class that overrides
// the ProcessMnemonic method.  If the mnemonic is correctly entered,  
// the message box will appear and the click event will be raised.  
public class MyMnemonicButton : Button
{
    // This method makes sure the control is selectable and the 
    // mneumonic is correct before displaying the message box
    // and triggering the click event.
    protected override bool ProcessMnemonic(char inputChar)
    {
        if (CanSelect && IsMnemonic(inputChar, this.Text))
        {
            MessageBox.Show("You've raised the click event " +
                "using the mnemonic.");
            this.PerformClick();
            return true;
        }
        return false;
    }
}

Comentarios

Cuando esta propiedad se establece trueen , el formulario recibirá todos los KeyPresseventos , KeyDowny KeyUp . Después de que los controladores de eventos del formulario hayan completado el procesamiento de la pulsación de tecla, la pulsación de tecla se asigna al control con el foco. Por ejemplo, si la KeyPreview propiedad se establece true en y el control seleccionado actualmente es , TextBoxdespués de controlar la pulsación de tecla los controladores de eventos del formulario, el TextBox control recibirá la tecla que se presionó. Para controlar los eventos de teclado solo en el nivel de formulario y no permitir que los controles reciban eventos de teclado, establezca la propiedad en el KeyPressEventArgs.Handled controlador truede eventos del KeyPress formulario en .

Puede usar esta propiedad para procesar la mayoría de las pulsaciones de teclas en la aplicación y controlar la pulsación de tecla o llamar al control adecuado para controlar la pulsación de teclas. Por ejemplo, cuando una aplicación usa claves de función, es posible que desee procesar las pulsaciones de teclas en el nivel de formulario en lugar de escribir código para cada control que pueda recibir eventos de pulsación de tecla.

Nota

Si un formulario no tiene controles visibles o habilitados, recibe automáticamente todos los eventos de teclado.

Nota

Se puede programar un control en un formulario para cancelar cualquier pulsación de tecla que reciba. Puesto que el control nunca envía estas pulsaciones de tecla al formulario, el formulario nunca los verá independientemente del valor de KeyPreview.

Se aplica a

Producto Versiones
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

Consulte también