Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ShortcutKey from string

I want to provider user with option to set ToolStripMenuItem.ShortcutKeys via configuration file, so I've figured out that I need somehow transform string to Keys.

I've already found how to do that for simple values using Enum.Parse, but it won't recognize formats like:

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

Q: Is there any standardized way of parsing stings (Ctrl+i) to Keys?

I'd like to avoid writing my own function that will split text into pieces and then handle each case/special string separately.

like image 374
Vyktor Avatar asked Dec 16 '22 06:12

Vyktor


1 Answers

The string you see in the Properties window for the ShortcutKeys property is generated by a TypeConverter. You can use that type converter in your own code as well. 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));

Do beware that I or Ctrl+Alt+Escape are not valid short-cut keys. KeysConverter will not complain, you'll get the exception when you assign the ShortCutKeys property. Wrap both with try/except to catch invalid config data.

like image 183
Hans Passant Avatar answered Dec 18 '22 12:12

Hans Passant