开发者

String to System.Windows.Input.Key

开发者 https://www.devze.com 2023-03-11 09:56 出处:网络
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

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开发者_如何学JAVA if/else's or switch statements?


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


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.


var key = Enum.Parse(typeof(Key), "Enter");

Case-insensitive option:

var key = Enum.Parse(typeof(Key), "enter", true);
0

精彩评论

暂无评论...
验证码 换一张
取 消