2009-07-24 19 views
8

Me gustaría cambiar todos los caracteres ingresados ​​en un cuadro de texto a mayúsculas. El código agregará el personaje, pero ¿cómo muevo el cursor a la derecha?Cómo mover el cuadro de texto a la derecha

private void textBox3_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    textBox3.Text += e.KeyChar.ToString().ToUpper(); 
    e.Handled = true; 
} 
+0

qué marco interfaz gráfica de usuario está usando? ¿Es esto ganar formas? wpf? Silverlight? –

+0

@ monkey_boys-Espero que mis cambios hayan dejado intacto tu significado. –

+0

Tenga en cuenta que 'textBox3.Text + = e.KeyChar.ToString(). ToUpper()' siempre agregará el carácter nuevo al final en el cuadro de texto, incluso si el símbolo de intercalación está en el medio del texto. –

Respuesta

18

establecer la propiedad CharacterCasing del TextBox-Upper; entonces no necesita procesarlo manualmente.

Tenga en cuenta que textBox3.Text += e.KeyChar.ToString().ToUpper(); añadirá el nuevo carácter al final de la cadena incluso si el cursor de entrada se encuentra en medio de la cadena (que la mayoría de los usuarios encontrarán muy confuso). Por la misma razón, no podemos asumir que el cursor de entrada debe aparecer al final de la cadena después de ingresar el carácter.

Si aún realmente quiere hacer esto en el código, algo como esto debería funcionar:

// needed for backspace and such to work 
if (char.IsControl(e.KeyChar)) 
{ 
    return; 
} 
int selStart = textBox3.SelectionStart; 
string before = textBox3.Text.Substring(0, selStart); 
string after = textBox3.Text.Substring(before.Length); 
textBox3.Text = string.Concat(before, e.KeyChar.ToString().ToUpper(), after); 
textBox3.SelectionStart = before.Length + 1; 
e.Handled = true; 
+0

+1: proporcioné una respuesta alternativa, ya que puede ser útil en otras situaciones. –

1

Esto conservará la ubicación del punto de inserción (pero persionally me gustaría ir con la respuesta dada por Fredrik Mörk)

private void textBox3_KeyPress(object sender, KeyPressEventArgs e)  
{   
    int selStart = textBox3.SelectionStart; 
    textBox3.Text += e.KeyChar.ToString().ToUpper();   
    textBox3.SelectionStart = selStart; 
    e.Handled = true; 
} 

SelectionStart en realidad podría ser llamado SelStart, no tengo un compilador a mano en el momento.

1

Si usted tiene que hacerlo de forma manual, puede utilizar

private void textBox3_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    textBox3.Text += e.KeyChar.ToString().ToUpper(); 
    textBox3.SelectionStart = textBox3.Text.Length; 
    e.Handled = true; 
} 

Pero el código anterior se inserta el nuevo carácter al final del texto. Si desea insertarlo en la posición del cursor:

private void textBox3_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    int selStart = textBox3.SelectionStart; 
    textBox3.Text = textBox3.Text.Insert(selStart,e.KeyChar.ToString().ToUpper()); 
    textBox3.SelectionStart = selStart + 1; 
    e.Handled = true; 
} 

Este código inserta el nuevo carácter en la posición del cursor y mueve el cursor a la izquierda del carácter que acaba de insertar.

Pero sigo pensando que configurar CharacterCasing es mejor.

0

Otro método es simplemente cambiar el valor de la propia KeyChar:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { 
     if ((int)e.KeyChar >= 97 && (int)e.KeyChar <= 122) { 
      e.KeyChar = (char)((int)e.KeyChar & 0xDF); 
     } 
    } 

Aunque, utilizando la propiedad CharacterCasing es la solución más fácil.

11
  tbNumber.SelectionStart = tbNumber.Text.ToCharArray().Length; 
      tbNumber.SelectionLength = 0; 
+0

Esta es una gran manera de agregar texto antes de que el usuario escriba. –

+0

+1, genial !!!!!! – ABCD

2
private void txtID_TextChanged(object sender, EventArgs e) 
{ 
    txtID.Text = txtID.Text.ToUpper(); 
    txtID.SelectionStart = txtID.Text.Length; 
} 
Cuestiones relacionadas