2009-05-12 12 views
10

ho bisogno di ottenere i args evento come un char, ma quando ho Prova a trasmettere l'enum Chiave ricevo completamente diverse lettere e simboli di quello che è stato passato in.Convertire una chiave System.Windows.Input.KeyEventArgs ad un char

Come si converte correttamente la chiave in un carattere?

Questo è quello che ho provato

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

Edit: anche io non ho la proprietà KeyCode sulle args. Li sto prendendo dall'evento InputManager.Current.PreNotifyInput.

risposta

2

Ci vuole un po 'per abituarsi, ma è sufficiente utilizzare i valori chiave stessi. Se stai cercando di limitare l'input agli alfanumerici e forse un po 'di più, il codice qui sotto potrebbe aiutarti.

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

All'interno del vostro gestore PreNotifyInput, provare qualcosa di simile:

 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]; 
      } 
     } 

Si pone più volte per i diversi eventi indirizzati, quindi si consiglia di filtrare per uno in particolare.

2

che il lavoro per me:

In base all'ultima voce ho scoperto che in WPF non esiste tale evento PreNotifyInput, ma ho trovato ed equivalente PreviewTextInput

prima cosa provare con un RegExp, ma non posso farlo funzionare, quindi io uso un semplice 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

So che questo è vecchio, ma nessuna delle risposte sembra effettivamente rispondere alla domanda. Il motivo per cui un altro char sta tornando è perché quando provi a lanciarlo su un valore char stai trasmettendo il valore enum a un 'carattere'. Tuttavia:

var keyPressed = e.key.ToString(); 

Funziona alla grande. Restituisce il tasto premuto come una stringa. Quindi controlli la lunghezza. Se è == 1, si tratta di un carattere, numero o simbolo. Se è maggiore di 1 è una chiave speciale.

Se si desidera solo il carattere si può poi fare keyPressed[0];

Questo è come lo faccio.

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) 
    } 
} 
Problemi correlati