2009-02-13 35 views
15

Voglio scrivere una funzione in questo modo,Come convertire un carattere in un valore Enum System.Windows.Input.Key equivalente?

 public System.Windows.Input.Key ResolveKey(char charToResolve) 
     { 
      // Code goes here, that resolves the charToResolve 
      // in to the Key enumerated value 
      // (For example with '.' as the character for Key.OemPeriod) 

     } 

So che posso scrivere un enorme switch-case per abbinare il personaggio, ma c'è qualche altro modo? La cosa con questa stringa della chiave enum potrebbe non corrispondere al carattere, quindi Enum.IsDefined non funzionerà

Qualche idea?

Update: Questo è in ambiente Windows

+0

Qual è l'ambiente? WinForms/asp.net? Qual è lo scopo di fare una cosa del genere? – shahkalpesh

risposta

23
[DllImport("user32.dll")] 
static extern short VkKeyScan(char ch); 

static public Key ResolveKey(char charToResolve) 
{ 
    return KeyInterop.KeyFromVirtualKey(VkKeyScan(charToResolve)); 
}
+1

'' VkKeyScan() 'usa il byte alto per codificare gli stati della chiave di modifica in modo che questo non funzioni per le lettere maiuscole perché' VkKeyScan() 'aggiunge il flag di maiusc. Se tu e il valore di ritorno di 'VkKeyScan()' con '0xFF' per cancellare quei flag funzionerà con lettere maiuscole. – shf301

7

provare a utilizzare il metodo di ConvertFrom della classe System.Windows.Input.KeyConverter.

+0

non funziona con '.' – Avram

+0

Questo non è pensato per essere usato in questo modo. Dai un'occhiata in Reflector e vedrai che supporta solo lettere, cifre e pochi altri tasti. Eccezioni degne di nota includono?, Che dovrebbe essere la stringa "OemQuestion" per essere convertita correttamente. – OwenP

1

Hi Basta convertire quel modo

Dim KeyConverter As New Forms.KeysConverter  
Dim S As String = KeyConverter.ConvertToString(e.Key) 
Dim O As System.Windows.Forms.Keys = KeyConverter.ConvertFrom(S) 
Dim ChValue As Integer = CType(O, Integer) 

Nel mio caso ho premere "Invio" sulla tastiera, O sta andando in ENTER {13} e ChValue sta andando in Codice carattere 13 Per TAB chiave lo farò ricevere il codice di carattere 9 in questo modo ad esempio.

1

Recentemente ho trovato un ottimo answer for similar question from Jon Hanna in grado di gestire gli stati chiave di controllo così:

Questo potrebbe essere più facilmente spiegato con un esempio di programma di ogni altra cosa:

namespace KeyFinder 
{ 
    class Program 
    { 
    [DllImport("user32.dll", CharSet = CharSet.Unicode)] 
    static extern short VkKeyScanEx(char ch, IntPtr dwhkl); 
    [DllImport("user32.dll")] 
    static extern bool UnloadKeyboardLayout(IntPtr hkl); 
    [DllImport("user32.dll")] 
    static extern IntPtr LoadKeyboardLayout(string pwszKLID, uint Flags); 
    public class KeyboardPointer : IDisposable 
    { 
     private readonly IntPtr pointer; 
     public KeyboardPointer(int klid) 
     { 
     pointer = LoadKeyboardLayout(klid.ToString("X8"), 1); 
     } 
     public KeyboardPointer(CultureInfo culture) 
     :this(culture.KeyboardLayoutId){} 
     public void Dispose() 
     { 
     UnloadKeyboardLayout(pointer); 
     GC.SuppressFinalize(this); 
     } 
     ~KeyboardPointer() 
     { 
     UnloadKeyboardLayout(pointer); 
     } 
     // Converting to System.Windows.Forms.Key here, but 
     // some other enumerations for similar tasks have the same 
     // one-to-one mapping to the underlying Windows API values 
     public bool GetKey(char character, out Keys key) 
     { 
     short keyNumber = VkKeyScanEx(character, pointer); 
     if(keyNumber == -1) 
     { 
      key = System.Windows.Forms.Keys.None; 
      return false; 
     } 
     key = (System.Windows.Forms.Keys)(((keyNumber & 0xFF00) << 8) | (keyNumber & 0xFF)); 
     return true; 
     } 
    } 
    private static string DescribeKey(Keys key) 
    { 
     StringBuilder desc = new StringBuilder(); 
     if((key & Keys.Shift) != Keys.None) 
     desc.Append("Shift: "); 
     if((key & Keys.Control) != Keys.None) 
     desc.Append("Control: "); 
     if((key & Keys.Alt) != Keys.None) 
     desc.Append("Alt: "); 
     return desc.Append(key & Keys.KeyCode).ToString(); 
    } 
    public static void Main(string[] args) 
    { 
     string testChars = "Aéש"; 
     Keys key; 
     foreach(var culture in (new string[]{"he-IL", "en-US", "en-IE"}).Select(code => CultureInfo.GetCultureInfo(code))) 
     { 
     Console.WriteLine(culture.Name); 
     using(var keyboard = new KeyboardPointer(culture)) 
      foreach(char test in testChars) 
      { 
      Console.Write(test); 
      Console.Write('\t'); 
      if(keyboard.GetKey(test, out key)) 
       Console.WriteLine(DescribeKey(key)); 
      else 
       Console.WriteLine("No Key"); 
      } 
     } 
     Console.Read();//Stop window closing 
    } 
    } 
} 

Uscita:

he-IL 
A Shift: A 
é No Key 
ש A 
en-US 
A Shift: A 
é No Key 
ש No Key 
en-IE 
A Shift: A 
é Control: Alt: E 
ש No Key 

(Anche se la vostra console potrebbe rovinare ש e/o E a seconda delle impostazioni e font).

leggere descrizioni complete da referenced answer

Problemi correlati