Interceptar las teclas del teclado en un TextBox

2248 vistas

Vamos a ayudarnos de los eventos de las teclas. Estos se producen cuando el TextBox tiene el foco y en el orden siguiente:

  • KeyDown: la tecla se ha presionado
  • KeyPress: se dispara si la tecla representa un carácter.
  • KeyUp: la tecla se ha soltado

Veamos un ejemplo de uso:

Creamos un proyecto WinForm C#, le añadimos 2 TextBox (textBox1 y textBox2) al form principal (Form1) y el código siguiente para que las teclas pulsadas en textBox1 se representen en textBox2



csharp
  1. // KeyPress Handler
  2. private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
  3. {
  4.     // mostramos los carácteres imprimibles
  5.     if (!char.IsControl(e.KeyChar))
  6.         textBox2.Text = textBox1.Text.Substring(0, textBox1.SelectionStart) +
  7.                         e.KeyChar.ToString() +
  8.                         textBox1.Text.Substring(textBox1.SelectionStart + textBox1.SelectionLength);
  9. }
  10.  
  11. // KeyDown Handler
  12. private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
  13. {
  14.     // Gestión tecla Back
  15.     if (e.KeyCode == Keys.Back && textBox1.Text.Length > 0)
  16.     {
  17.         if (textBox1.SelectionLength > 0)
  18.         {
  19.             // borramos selección
  20.             textBox2.Text = textBox1.Text.Substring(0, textBox1.SelectionStart) +
  21.                             textBox1.Text.Substring(textBox1.SelectionStart + textBox1.SelectionLength);
  22.         }
  23.         else if (textBox1.SelectionStart > 0)
  24.         {
  25.             // borramos carácter anterior al cursor
  26.             if (textBox1.SelectionStart == textBox1.Text.Length)
  27.                 textBox2.Text = textBox1.Text.Substring(0, textBox1.Text.Length-1);
  28.             else
  29.                 textBox2.Text = textBox1.Text.Substring(0, textBox1.SelectionStart-1) +
  30.                                 textBox1.Text.Substring(textBox1.SelectionStart +
  31.                                                         textBox1.SelectionLength);
  32.         }
  33.     }
  34.     // Tecla Delete (suppr)
  35.     else if (e.KeyCode == Keys.Delete &&  textBox1.Text.Length > 0)
  36.     {
  37.         // el cursor está a final de cadena
  38.         if (textBox1.SelectionStart == textBox1.Text.Length)
  39.         {
  40.             // borrado último carácter por Shift+Del
  41.             if (e.Shift)
  42.                 textBox2.Text = textBox1.Text.Substring(0, textBox1.Text.Length-1);
  43.         }
  44.         else
  45.         {
  46.             // tomamos todos los carácteres a la izquierda del cursor
  47.             textBox2.Text = textBox1.Text.Substring(0, textBox1.SelectionStart);
  48.             if (textBox1.SelectionLength != 0)
  49.                 // borramos selección
  50.                 textBox2.AppendText(textBox1.Text.Substring(textBox1.SelectionStart +
  51.                                                             textBox1.SelectionLength));
  52.             else
  53.             {
  54.                 // si se pulsa la tecla Control, borramos todos los carácteres a la derecha del cursor,
  55.                 // sino, borramos sólo uno
  56.                 if (!e.Control)
  57.                     textBox2.Text = textBox1.Text.Substring(0, textBox1.SelectionStart) +
  58.                                     textBox1.Text.Substring(textBox1.SelectionStart+1);
  59.             }
  60.         }
  61.     }
  62.     // pegar (Ctrl+V) o (Shift+insert).
  63.     else if ((e.Shift && e.KeyCode == Keys.Insert) || (e.Control && e.KeyCode == Keys.V))
  64.     {
  65.         // datos en el porta papeles
  66.         IDataObject cpdata = Clipboard.GetDataObject();
  67.       // miramos si cpdata contiene texto
  68.         if (cpdata != null && cpdata.GetDataPresent(string.Empty.GetType()))
  69.         {
  70.             string data = cpdata.GetData(string.Empty.GetType()).ToString();
  71.             bool print = false;
  72.             // gestión de carácteres no imprimibles (como la tabulación por ejemplo)
  73.             for (int i=0; i<data.Length-1; i++)
  74.             {
  75.                 if (char.IsControl(data, i) && print)
  76.                 {
  77.                     data = data.Substring(0, i);
  78.                     break;
  79.                 }
  80.                 else if (!char.IsControl(data, i) && !print)
  81.                     print = true;
  82.             }
  83.             textBox2.Text = textBox1.Text.Substring(0, textBox1.SelectionStart) +
  84.                             data +
  85.                             textBox1.Text.Substring(textBox1.SelectionStart + textBox1.SelectionLength);
  86.         }
  87.     }
  88. }