views:

2961

answers:

4

I want to write a function like so,

        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)

        }

I know I can write a huge Switch-case to match the character, but is there any other way? The thing with this is the Key enum's string may not match with the character so Enum.IsDefined will not work

Any ideas?

Update: This is in Windows environment

A: 

You would need to do this with a large switch statement.

switch(charToResolve) {
 case 'a':
  return key.OemA;
  break;
.
.
.
Suroot
+1  A: 

Try using the ConvertFrom method of the System.Windows.Input.KeyConverter class.

Joacim Andersson
doesn't working with '.'
Avram
This isn't meant to be used that way. Take a peek at it in Reflector and you'll see it only supports letters, digits, and a few other keys. Notable exceptions include ?, which would need to be the string "OemQuestion" to get converted properly.
OwenP
Correct, but KeyConverter is still used by calling ConvertToString(value As Object) As String.
AMissico
+6  A: 
[DllImport("user32.dll")]
static extern short VkKeyScan(char ch);

static public Key ResolveKey(char charToResolve)
{
    return KeyInterop.KeyFromVirtualKey(VkKeyScan(charToResolve));
}
xcud
+7  A: 

Avoid the API call in the "accepted answer" and use KeyConverter.ConvertToString. That is what it is for.

AMissico