converting a string to Keys in C#

Alex picture Alex · Aug 21, 2012 · Viewed 7k times · Source

Lets say we store KeyCode value as a string. How do you convert it back to KeyCode?

For example, I've captured a key on keydown event:

string modifier = e.Modifiers.ToString(); // Control
string key_string = e.KeyCode.ToString(); // D1

How to do the following ?

Keys old_key_restored = (Keys)key_string;

Code above doesn't work.

EDIT: Daniel is a life savior ;)

Keys key_restored = (Keys) Enum.Parse(typeof(Keys), key_key);

Answer

Daniel A. White picture Daniel A. White · Aug 21, 2012

Its just an enum so you can use Enum.TryParse