KeyPressEventArgs KeyPressEventArgs KeyPressEventArgs KeyPressEventArgs Class

Definición

Proporciona datos para el evento KeyPress.Provides data for the KeyPress event.

public ref class KeyPressEventArgs : EventArgs
[System.Runtime.InteropServices.ComVisible(true)]
public class KeyPressEventArgs : EventArgs
type KeyPressEventArgs = class
    inherit EventArgs
Public Class KeyPressEventArgs
Inherits EventArgs
Herencia
KeyPressEventArgsKeyPressEventArgsKeyPressEventArgsKeyPressEventArgs
Atributos

Ejemplos

El ejemplo siguiente se muestra cómo utilizar el KeyPressEventArgs para contar teclas a medida que se presionan y mostrar los resultados después de cada pulsación de tecla.The following example illustrates using the KeyPressEventArgs to count keys as they are pressed and to display the results after each key press. Handled a continuación, establecido en True para mantener el sistema operativo desde más procesa la clave.Handled is then set to true to keep the operating system from further processing the key. El ejemplo supone un formulario con un TextBox coloca en él.The example assumes a form with a TextBox placed on it.

public ref class myKeyPressClass
{
private:
   static long keyPressCount = 0;
   static long backspacePressed = 0;
   static long returnPressed = 0;
   static long escPressed = 0;
   TextBox^ textBox1;
   void myKeyCounter( Object^ sender, KeyPressEventArgs^ ex )
   {
      switch ( ex->KeyChar )
      {
            // Counts the backspaces.
         case '\b':
         backspacePressed = backspacePressed + 1;
         break;

            // Counts the ENTER keys.
         case '\r':
         returnPressed = returnPressed + 1;
         break;

            // Counts the ESC keys.  
         case (char)27:
         escPressed = escPressed + 1;
         break;
            
            // Counts all other keys.
         default:
         keyPressCount = keyPressCount + 1;
         break;
      }
      textBox1->Text = String::Concat( 
         backspacePressed, " backspaces pressed\r\n",
         escPressed, " escapes pressed\r\n",
         returnPressed, " returns pressed\r\n",
         keyPressCount, " other keys pressed\r\n" );
      ex->Handled = true;
   }
};
public class myKeyPressClass 
 {
     static long keyPressCount = 0 ;
     static long backspacePressed =  0;
     static long returnPressed = 0 ;
     static long escPressed = 0 ;
     private TextBox textBox1 = new TextBox();
     private void myKeyCounter(object sender, KeyPressEventArgs ex)
     {
     switch(ex.KeyChar)
     {
             // Counts the backspaces.
         case '\b':
         backspacePressed = backspacePressed + 1;
         break ;
             // Counts the ENTER keys.
         case '\r':
         returnPressed = returnPressed + 1 ;
         break ;
             // Counts the ESC keys.  
         case (char)27:
         escPressed = escPressed + 1 ;
         break ;
             // Counts all other keys.
         default:
         keyPressCount = keyPressCount + 1 ;
         break;
     }
     
     textBox1.Text = 
         backspacePressed + " backspaces pressed\r\n" + 
         escPressed + " escapes pressed\r\n" +
         returnPressed + " returns pressed\r\n" +
         keyPressCount + " other keys pressed\r\n" ;
     ex.Handled = true ;
     }
 }
Public Class myKeyPressClass
    Private Shared keyPressCount As Long = 0
    Private Shared backspacePressed As Long = 0
    Private Shared returnPressed As Long = 0
    Private Shared escPressed As Long = 0
    Private textBox1 As TextBox
    
    Private Sub myKeyCounter(sender As Object, ex As KeyPressEventArgs)
        Select Case ex.KeyChar
            ' Counts the backspaces.
            Case ControlChars.Back
                backspacePressed = backspacePressed + 1
            ' Counts the ENTER keys.
            Case ControlChars.Lf
                returnPressed = returnPressed + 1
            ' Counts the ESC keys.  
            Case Convert.ToChar(27)
                escPressed = escPressed + 1
            ' Counts all other keys.
            Case Else
                keyPressCount = keyPressCount + 1
        End Select
        
        textBox1.Text = backspacePressed & " backspaces pressed" & _
            ControlChars.Lf & ControlChars.Cr & escPressed & _
            " escapes pressed" & ControlChars.CrLf & returnPressed & _
            " returns pressed" & ControlChars.CrLf & keyPressCount & _
            " other keys pressed" & ControlChars.CrLf
        ex.Handled = True
    End Sub 'myKeyCounter
End Class 'myKeyPressClass

Debe crear una nueva instancia de esta clase.You must create a new instance of this class. También debe establecer el controlador de eventos.You must also set the event handler. Puede hacerlo en el constructor para la clase.You can do this in the constructor for your class.

public:
   myKeyPressClass^ myKeyPressHandler;

   Form1()
   {
      myKeyPressHandler = gcnew myKeyPressClass;

      InitializeComponent();

      textBox1->KeyPress += gcnew KeyPressEventHandler(
         myKeyPressHandler, &myKeyPressClass::myKeyCounter );
   }
myKeyPressClass myKeyPressHandler = new myKeyPressClass();
public Form1()
{
     InitializeComponent();
 
     textBox1.KeyPress += new KeyPressEventHandler(myKeyPressHandler.myKeyCounter);
}
Private myKeyPressHandler As New myKeyPressClass()

Public Sub New()
    InitializeComponent()
    
    AddHandler textBox1.KeyPress, AddressOf myKeyPressHandler.myKeyCounter
End Sub 'New

Cuando se provoca el evento especificado en el control, se llama al método asociado y la aplicación puede ejecutar código en respuesta al evento.When the specified event is raised in the control, the attached method is called and the application can execute code in response to the event.

Comentarios

Un KeyPressEventArgs especifica el carácter que se compone cuando el usuario presiona una tecla.A KeyPressEventArgs specifies the character that is composed when the user presses a key. Por ejemplo, cuando el usuario presiona MAYÚS + K, el KeyChar propiedad devuelve una k mayúscula.For example, when the user presses SHIFT + K, the KeyChar property returns an uppercase K.

Un KeyPress evento tiene lugar cuando el usuario presiona una tecla.A KeyPress event occurs when the user presses a key. Dos eventos que están estrechamente relacionados con el KeyPress son eventos KeyUp y KeyDown.Two events that are closely related to the KeyPress event are KeyUp and KeyDown. El KeyDown evento precede a cada KeyPress eventos cuando el usuario presiona una tecla y un KeyUp evento tiene lugar cuando el usuario suelta una tecla.The KeyDown event precedes each KeyPress event when the user presses a key, and a KeyUp event occurs when the user releases a key. Cuando el usuario mantiene presionada una tecla, duplicar KeyDown y KeyPress cada vez que se repite el carácter se producen eventos.When the user holds down a key, duplicate KeyDown and KeyPress events occur each time the character repeats. Una KeyUp evento se genera después de su lanzamiento.One KeyUp event is generated upon release.

Con cada KeyPress evento, un KeyPressEventArgs se pasa.With each KeyPress event, a KeyPressEventArgs is passed. Un KeyEventArgs se pasa con cada KeyDown y KeyUp eventos.A KeyEventArgs is passed with each KeyDown and KeyUp event. Un KeyEventArgs especifica si se han presionado teclas modificadoras (CTRL, ALT o MAYÚS) junto con otra clave.A KeyEventArgs specifies whether any modifier keys (CTRL, SHIFT, or ALT) were pressed along with another key. (Esta información de modificador también puede obtenerse a través de la ModifierKeys propiedad de la Control clase.)(This modifier information can also be obtained through the ModifierKeys property of the Control class.)

Establecer Handled a true para cancelar la KeyPress eventos.Set Handled to true to cancel the KeyPress event. Esto evita que el control de presionar la tecla de procesamiento.This keeps the control from processing the key press.

Nota

Algunos controles procesarán ciertas pulsaciones de teclas en KeyDown.Some controls will process certain key strokes on KeyDown. Por ejemplo, RichTextBox procesa la tecla ENTRAR antes KeyPress se llama.For example, RichTextBox processes the Enter key before KeyPress is called. En tales casos, no puede cancelar la KeyPress eventos y debe cancelar la pulsación de tecla de KeyDown en su lugar.In such cases, you cannot cancel the KeyPress event, and must cancel the key stroke from KeyDown instead.

Para obtener información sobre el modelo de eventos, vea controlar y provocar eventos.For information about the event model, see Handling and Raising Events.

Constructores

KeyPressEventArgs(Char) KeyPressEventArgs(Char) KeyPressEventArgs(Char) KeyPressEventArgs(Char)

Inicializa una nueva instancia de la clase KeyPressEventArgs.Initializes a new instance of the KeyPressEventArgs class.

Propiedades

Handled Handled Handled Handled

Obtiene o establece un valor que indica si se controló el evento KeyPress.Gets or sets a value indicating whether the KeyPress event was handled.

KeyChar KeyChar KeyChar KeyChar

Obtiene o establece el carácter correspondiente a la tecla presionada.Gets or sets the character corresponding to the key pressed.

Métodos

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Inherited from Object)

Se aplica a

Consulte también: