String in System.Windows.Input.Key

I need a function that takes a string as an argument and returns System.Windows.Input.Key. For instance:

var x = StringToKey("enter"); // Returns Key.Enter var y = StringToKey("a"); // Returns Key.A 

Is there a way to do this differently than if / else or switch statements?

+6
source share
3 answers

Take a look at KeyConverter , it can convert Key to and from string .

 KeyConverter k = new KeyConverter(); Key mykey = (Key)k.ConvertFromString("Enter"); if (mykey == Key.Enter) { Text = "Enter Key Found"; } 
+15
source

The key is an enumeration, so you can parse it like any enumeration:

 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 must match exactly (well, almost, this is a case-insensitive comparison due to this parameter true ) the name of the enumeration value.

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

Case insensitive:

 var key = Enum.Parse(typeof(Key), "enter", true); 
+3
source

Source: https://habr.com/ru/post/889830/


All Articles