ToolStripMenuItem mi = new ToolStripMenuItem();
var value = new KeysConverter().ConvertFromString("PageUp");
// value = Enum.Parse(typeof (Keys), "PageUp");
var cast = (Keys) value;
mi.ShortcutKeys = cast;
I'm trying to convert the string "PageUp" into the appropriate System.Windows.Forms.Keys value.
However, both parsing approaches (Enum.Parse() vs. KeysConverter.ConvertFromString()) set value to LButton | Space, which leads to an InvalidEnumArgumentException on the last line.
Background:
System.Windows.Forms.Keys is a Flags enumEnum.Parse works correctly. How do I correctly parse "PageUp" into Keys.PageUp?
Update:
Silly me. the parsing works correctly.
ToolStripMenuItem mi = new ToolStripMenuItem();
mi.ShortcutKeys = Keys.PageUp;
but this one throws the above mentioned exception.
So after realising I barked up the wrong tree:
How can one assign Keys.PageUp to ToolStripMenuItem.ShortcutKeys?
As it turns out, ShortcutKeys uses this logic to accept possible shortcut keys (however, None is always accepted):
public static bool IsValidShortcut(Keys shortcut) {
// should have a key and one or more modifiers.
Keys keyCode = (Keys)(shortcut & Keys.KeyCode);
Keys modifiers = (Keys)(shortcut & Keys.Modifiers);
if (shortcut == Keys.None) {
return false;
}
else if ((keyCode == Keys.Delete) || (keyCode == Keys.Insert)) {
return true;
}
else if (((int)keyCode >= (int)Keys.F1) && ((int)keyCode <= (int)Keys.F24)) {
// function keys by themselves are valid
return true;
}
else if ((keyCode != Keys.None) && (modifiers != Keys.None)) {
switch (keyCode) {
case Keys.Menu:
case Keys.ControlKey:
case Keys.ShiftKey:
// shift, control and alt arent valid on their own.
return false;
default:
if (modifiers == Keys.Shift) {
// shift + somekey isnt a valid modifier either
return false;
}
return true;
}
}
// has to have a valid keycode and valid modifier.
return false;
}
So you can use, None, Delete, Insert, F1-F12 keys on their own, or all other keys with Alt, Ctrl, and, only as additional, Shift key modifier.
The second you are asking the right question, you'll find the answer....
this one clarified it for me: Setting the Windows Forms ToolStripMenuItem ShortcutKeys property to numpad key does not work
quote from the accepted answer there:
You must use Ctrl or Alt in shortcuts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With