ShortcutKey from string

I want a provider user with the ability to install ToolStripMenuItem.ShortcutKeys through the configuration file, so I found out that I need to somehow convert the string to Keys .

I already found how to do this for simple values ​​using Enum.Parse , but it will not recognize formats such as:

  • Ctrl+i (with a space at the end)
  • i
  • Ctrl+Alt+Esc

Q: Is there a standardized way to parse stings ( Ctrl+i ) to Keys ?

I would like not to write my own function, which divides the text into pieces, and then processes each individual case / special line.

+4
source share
2 answers

The string that you see in the Properties window for the ShortcutKeys property is generated using TypeConverter. You can use this type of converter in your own code too. Like this:

  var txt = "Ctrl+I"; var cvt = new KeysConverter(); var key = (Keys)cvt.ConvertFrom(txt); System.Diagnostics.Debug.Assert(key == (Keys.Control | Keys.I)); 

Beware that Ctrl+Alt+Escape not valid for I or Ctrl+Alt+Escape . KeysConverter will not complain, you will get an exception if you assign the ShortCutKeys property. Wrap both with try /, except to catch the wrong configuration data.

+11
source

Yes, you can separate the values ​​with - however, your string still needs to be massed, because Ctrl and Esc not valid Keys values. They must still be valid values. Therefore, consider the following code:

 var keys = "Ctrl+Alt+Esc"; keys = keys.Replace("+", ",").Replace("Ctrl", "Control").Replace("Esc", "Escape"); var k = (Keys)Enum.Parse(typeof(Keys), keys); 

Next, here is the code in the Enum class that is going to select this:

 string[] array = value.Split(Enum.enumSeperatorCharArray); ulong[] array2; string[] array3; Enum.GetCachedValuesAndNames(runtimeType, out array2, out array3, true, true); for (int i = 0; i < array.Length; i++) { array[i] = array[i].Trim(); bool flag = false; int j = 0; while (j < array3.Length) { if (ignoreCase) { if (string.Compare(array3[j], array[i], StringComparison.OrdinalIgnoreCase) == 0) { goto IL_152; } } else { if (array3[j].Equals(array[i])) { goto IL_152; } } j++; continue; IL_152: ulong num2 = array2[j]; num |= num2; flag = true; break; } if (!flag) { parseResult.SetFailure(Enum.ParseFailureKind.ArgumentWithParameter, "Arg_EnumValueNotFound", value); return false; } } 

enumSeperatorCharArray value:

 private static readonly char[] enumSeperatorCharArray = new char[] { ',' }; 
0
source

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


All Articles