2009-05-12 22 views
10

que necesito para obtener los argumentos de eventos como char, pero cuando trato de fundición de la enumeración clave consigo completamente diferentes letras y símbolos de lo que se ha pasado.Convertir una clave System.Windows.Input.KeyEventArgs a un char

¿Cómo convertir correctamente la clave a un char?

Esto es lo que he tratado

ObserveKeyStroke(this, new ObervableKeyStrokeEvent((char)((KeyEventArgs)e.StagingItem.Input).Key)); 

Edit: Asimismo, no tienen la propiedad KeyCode en los argumentos. Los obtengo del evento InputManager.Current.PreNotifyInput.

Respuesta

2

Tarda un poco en acostumbrarse, pero puede usar los valores clave por sí mismos. Si intenta limitar la entrada a caracteres alfanuméricos y tal vez un poco más, el siguiente código puede ayudar.

private bool bLeftShiftKey = false; 
    private bool bRightShiftKey = false; 

    private bool IsValidDescriptionKey(Key key) 
    { 
     //KEYS ALLOWED REGARDLESS OF SHIFT KEY 

     //various editing keys 
     if (
     key == Key.Back || 
     key == Key.Tab || 
     key == Key.Up || 
     key == Key.Down || 
     key == Key.Left || 
     key == Key.Right || 
     key == Key.Delete || 
     key == Key.Space || 
     key == Key.Home || 
     key == Key.End 
     ) { 
      return true; 
     } 

     //letters 
     if (key >= Key.A && key <= Key.Z) 
     { 
      return true; 
     } 

     //numbers from keypad 
     if (key >= Key.NumPad0 && key <= Key.NumPad9) 
     { 
      return true; 
     } 

     //hyphen 
     if (key == Key.OemMinus) 
     { 
      return true; 
     } 

     //KEYS ALLOWED CONDITITIONALLY DEPENDING ON SHIFT KEY 

     if (!bLeftShiftKey && !bRightShiftKey) 
     { 
      //numbers from keyboard 
      if (key >= Key.D0 && key <= Key.D9) 
      { 
       return true; 
      } 
     } 

     return false; 
    } 

    private void cboDescription_PreviewKeyDown(object sender, KeyEventArgs e) 
    { 
     if (e.Key == Key.LeftShift) 
     { 
      bLeftShiftKey = true; 
     } 

     if (e.Key == Key.RightShift) 
     { 
      bRightShiftKey = true; 
     } 

     if (!IsValidDescriptionKey(e.Key)) 
     { 
      e.Handled = true; 
     } 
    } 

    private void cboDescription_PreviewKeyUp(object sender, KeyEventArgs e) 
    { 
     if (e.Key == Key.LeftShift) 
     { 
      bLeftShiftKey = false; 
     } 

     if (e.Key == Key.RightShift) 
     { 
      bRightShiftKey = false; 
     } 
    } 
0

Dentro de su manejador PreNotifyInput, intentar algo como esto:

 if (e.StagingItem.Input is System.Windows.Input.TextCompositionEventArgs) 
     { 
      if (!String.IsNullOrEmpty((e.StagingItem.Input as System.Windows.Input.TextCompositionEventArgs).Text)) 
      { 
       Char c = (e.StagingItem.Input as System.Windows.Input.TextCompositionEventArgs).Text[0]; 
      } 
     } 

Plantea varias veces para los diferentes eventos enrutados, por lo que puede filtrar por una en particular.

2

que el trabajo para mí:

Sobre la base de la última entrada me encontré con que en WPF no hay tal caso PreNotifyInput, pero he encontrado y equivalentes PreviewTextInput

Primero lo intento con un RegExp, pero no puedo hacer que funcione, entonces uso un simple indexOf.

private bool ValidChar(string _char) 
{ 
    string Lista = @" ! "" # $ % & ' () * + , - ./0 1 2 3 4 5 6 7 8 9 : ; <=> ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z "; 
    return Lista.IndexOf(_char.ToUpper()) != -1; 
    //System.Text.RegularExpressions.Regex RegVal = new System.Text.RegularExpressions.Regex(@"(?<LETRAS>[A-Z]+)+(?<NUMERO>[0-9]+)+(?<CAR>[!|""|#|$|%|&|'|(|)|*|+|,|\-|.|/|:|;|<|=|>|?|@]+)+"); 
    //return RegVal.IsMatch(_char); 
} 

private void textBoxDescripcion_PreviewTextInput(object sender, TextCompositionEventArgs e) 
{ 
    if (!ValidChar(e.Text)) 
     e.Handled = true; 
} 
1

Sé que esto es antiguo, pero ninguna de las respuestas parece responder realmente a la pregunta. La razón por la que un char diferente está regresando es porque cuando intentas lanzarlo a un char, estás convirtiendo el valor enum en un 'char'. Sin embargo:

var keyPressed = e.key.ToString(); 

Funciona muy bien. Devuelve la tecla presionada como una cadena. Luego, comprueba la longitud. Si es == 1, entonces es un carácter, número o símbolo. Si es mayor que 1, es una clave especial.

Si lo que desea es el carbón a continuación, puede hacer keyPressed[0];

Esta es la forma en que lo hago.

private void scrollViewer_KeyDown(object sender, KeyEventArgs e) 
{ 
    if (!e.IsRepeat) 
    { 
     var keyPressed = e.Key.ToString(); 
     if(keyPressed.Length == 1) 
      CharKeyPressed(keyPressed[0]); 
     else if(keyPressed.Length > 1) 
      HandleSpecialKey(keyPressed) 
    } 
}