Este artigo foi traduzido por máquina. Para visualizar o arquivo em inglês, marque a caixa de seleção Inglês. Você também pode exibir o texto Em inglês em uma janela pop-up, movendo o ponteiro do mouse sobre o texto.
Tradução
Inglês

Classe KeyEventArgs

 

Fornece dados para o evento KeyDown ou KeyUp.

Namespace:   System.Windows.Forms
Assembly:  System.Windows.Forms (em System.Windows.Forms.dll)

System.Object
  System.EventArgs
    System.Windows.Forms.KeyEventArgs

[ComVisibleAttribute(true)]
public class KeyEventArgs : EventArgs

NomeDescrição
System_CAPS_pubmethodKeyEventArgs(Keys)

Inicializa uma nova instância da classe KeyEventArgs.

NomeDescrição
System_CAPS_pubpropertyAlt

Obtém um valor que indica se a tecla ALT foi pressionada.

System_CAPS_pubpropertyControl

Obtém um valor que indica se a tecla CTRL foi pressionada.

System_CAPS_pubpropertyHandled

Obtém ou define um valor que indica se o evento foi tratado.

System_CAPS_pubpropertyKeyCode

Obtém o código de teclado de um evento KeyDown ou KeyUp.

System_CAPS_pubpropertyKeyData

Obtém os dados da chave de um evento KeyDown ou KeyUp.

System_CAPS_pubpropertyKeyValue

Obtém o valor de teclado para um evento KeyDown ou KeyUp.

System_CAPS_pubpropertyModifiers

Obtém os sinalizadores de modificador para um KeyDown ou KeyUp eventos. Os sinalizadores indicam qual combinação de teclas CTRL, SHIFT e ALT foi pressionada.

System_CAPS_pubpropertyShift

Obtém um valor que indica se a tecla SHIFT foi pressionada.

System_CAPS_pubpropertySuppressKeyPress

Obtém ou define um valor que indica se o evento de chave deve ser passado para o controle subjacente.

NomeDescrição
System_CAPS_pubmethodEquals(Object)

Verifica se o objeto especificado é igual ao objeto atual. (Herdado de Object.)

System_CAPS_protmethodFinalize()

Permite que um objeto tente liberar recursos e executar outras operações de limpeza antes que ele seja recuperado pela coleta de lixo. (Herdado de Object.)

System_CAPS_pubmethodGetHashCode()

Serve como a função de hash padrão.(Herdado de Object.)

System_CAPS_pubmethodGetType()

Obtém o Type da instância atual.(Herdado de Object.)

System_CAPS_protmethodMemberwiseClone()

Cria uma cópia superficial do Object atual.(Herdado de Object.)

System_CAPS_pubmethodToString()

Retorna uma string que representa o objeto atual.(Herdado de Object.)

A T:System.Windows.Forms.KeyEventArgs, which specifies the key the user pressed and whether any modifier keys (CTRL, ALT, and SHIFT) were pressed at the same time, is passed with each E:System.Windows.Forms.Control.KeyDown or E:System.Windows.Forms.Control.KeyUp event.

The E:System.Windows.Forms.Control.KeyDown event occurs when the user presses any key. The E:System.Windows.Forms.Control.KeyUp event occurs when the user releases the key. Duplicate E:System.Windows.Forms.Control.KeyDown events occur each time the key repeats, if the key is held down, but only one E:System.Windows.Forms.Control.KeyUp event is generated when the user releases the key.

The E:System.Windows.Forms.Control.KeyPress event also occurs when a key is pressed. A T:System.Windows.Forms.KeyPressEventArgs is passed with each E:System.Windows.Forms.Control.KeyPress event, and specifies the character that was composed as a result of each key press.

For information about the event model, see Handling and Raising Events.

The following code examples demonstrate how to detect the state of a key press.

Example 1

The following code example demonstrates how to use the E:System.Windows.Forms.Control.KeyDown event with the T:System.Windows.Forms.Help class to display pop-up style Help to the user of the application. The example uses the T:System.Windows.Forms.KeyEventArgs properties passed to the event handler method to filter for all variations of pressing the F1 key with a modifier key. When the user presses any variation of F1 that includes any keyboard modifier, the T:System.Windows.Forms.Help class displays a pop-up window, similar to a T:System.Windows.Forms.ToolTip, near the control. If the user presses ALT+F2, a different Help pop-up is displayed with additional information.

private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    // Determine whether the key entered is the F1 key. If it is, display Help.
    if(e.KeyCode == Keys.F1 && (e.Alt || e.Control || e.Shift))
    {
        // Display a pop-up Help topic to assist the user.
        Help.ShowPopup(textBox1, "Enter your name.", new Point(textBox1.Bottom, textBox1.Right));
    }
    else if(e.KeyCode == Keys.F2 && e.Modifiers == Keys.Alt)
    {
        // Display a pop-up Help topic to provide additional assistance to the user.
        Help.ShowPopup(textBox1, "Enter your first name followed by your last name. Middle name is optional.",
            new Point(textBox1.Top, this.textBox1.Left));
    }
}

Example 2

The following example determines whether the user pressed ALT+E, and if the mouse pointer is over a T:System.Windows.Forms.TreeNode, allows the user to edit that T:System.Windows.Forms.TreeNode.

private void treeView1_KeyDown(object sender, KeyEventArgs e)
{
   /* If the 'Alt' and 'E' keys are pressed,
      * allow the user to edit the TreeNode label. */
   if(e.Alt && e.KeyCode == Keys.E)

   {
      treeView1.LabelEdit = true;
      // If there is a TreeNode under the mose cursor, begin editing. 
      TreeNode editNode = treeView1.GetNodeAt(
         treeView1.PointToClient(System.Windows.Forms.Control.MousePosition));
      if(editNode != null)
      { 
         editNode.BeginEdit();
      }
   }
}

private void treeView1_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
{
   // Disable the ability to edit the TreeNode labels.
   treeView1.LabelEdit = false;
}

Example 3

The following example determines whether the user pressed a non-numeric key, and if so, cancels the E:System.Windows.Forms.Control.KeyPress event by using the P:System.Windows.Forms.KeyEventArgs.Handled property.

// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;

// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    // Initialize the flag to false.
    nonNumberEntered = false;

    // Determine whether the keystroke is a number from the top of the keyboard.
    if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
    {
        // Determine whether the keystroke is a number from the keypad.
        if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
        {
            // Determine whether the keystroke is a backspace.
            if(e.KeyCode != Keys.Back)
            {
                // A non-numerical keystroke was pressed.
                // Set the flag to true and evaluate in KeyPress event.
                nonNumberEntered = true;
            }
        }
    }
    //If shift key was pressed, it's not a number.
    if (Control.ModifierKeys == Keys.Shift) {
        nonNumberEntered = true;
    }
}

// This event occurs after the KeyDown event and can be used to prevent
// characters from entering the control.
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    // Check for the flag being set in the KeyDown event.
    if (nonNumberEntered == true)
    {
        // Stop the character from being entered into the control since it is non-numerical.
        e.Handled = true;
    }
}

.NET Framework
Disponível desde 1.1

Quaisquer membros estáticos públicos ( Compartilhado no Visual Basic) desse tipo são thread-safe. Não há garantia de que qualquer membro de instância seja thread-safe.

Retornar ao início
Mostrar: