Вопрос

I have a ToolStripMenuItem that serves as a drop down menu attached to the MenuStrip of my Form. The contents of this menu change depending on the status of the rest of the form and are populated in a loop.

The problem is that now I would like to add the functionality that the items in this menu have a keyboard shortcut based on their position in the list. The first item in the list should be Ctrl+1, the second Ctrl+2, etc.

Since ShortcutKeys is set using the Keys enum I do not know how I could map an incrementing value to the proper values in the enum. I had hoped something like this would work, but it did not:

newToolStripMenuItem.ShortcutKeys = Keys.Control | (Keys.D0 + menuItemNumber++);

Edit

There may be something else going on. According to this asker my initial solution should have worked, and the solution proposed by Migol produces the same result. The value in ShortcutKeys is shown to be some odd combination of characters with no apparent pattern.

Это было полезно?

Решение 2

This is embarrassing, but the problem completely unrelated to anything mentioned in this post. It was a stupid mistake made by my own bad programming habits in combination with a typo.

In my original ask I changed the name of my local variable from processorToolStripMenuItem to newToolStripMenuItem since this made more sense out of the context of the application. The item I was adding it to was a field named procesorToolStripMenuItem which as you can see is missing an 's'.

For the line of code setting the keyboard shortcut I made the same typo and was thus setting the keyboard shortcut of the wrong thing. They should never have been named something so similar to one another in the first place.

Другие советы

You can use Enum.Parse method like this:

string enumName = "D" + menuItemNumber++;
newToolStripMenuItem.ShortcutKeys = Keys.Control | (Keys)Enum.Parse(typeof(Keys), enumName);

Enum.Parse documentation

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top