Reputation: 8202
I need a function that takes a String as an argument, and returns a System.Windows.Input.Key. E.G:
var x = StringToKey("enter"); // Returns Key.Enter
var y = StringToKey("a"); // Returns Key.A
Is there any way to do this other than if/else's or switch statements?
Upvotes: 6
Views: 9947
Reputation: 78447
var key = Enum.Parse(typeof(Key), "Enter");
Case-insensitive option:
var key = Enum.Parse(typeof(Key), "enter", true);
Upvotes: 3
Reputation: 17858
Take a look at KeyConverter, it can convert a Key
to and from a string
.
KeyConverter k = new KeyConverter();
Key mykey = (Key)k.ConvertFromString("Enter");
if (mykey == Key.Enter)
{
Text = "Enter Key Found";
}
Upvotes: 20
Reputation: 36852
Key is an enum, so you can parse it like any enum:
string str = /* name of the key */;
Key key;
if(Enum.TryParse(str, true, out key))
{
// use key
}
else
{
// str is not a valid key
}
Keep in mind that the string has to match exactly (well, almost; it's a case insensitive comparison because of that true
parameter) the name of the enumeration value.
Upvotes: 9