I've got a contextual menu in which elements are added dynamically.
I want to assign shortcut keys to those elements (1 - 9) but I don't know how.
Can anyone help me?
xem = 49; //(ASCII code for 1)
while (drCupoane.Read())
{
ToolStripMenuItem mnu = new ToolStripMenuItem();
mnu.Text = drC[1].ToString();
mnu.ToolTipText = "Cupon";
char c = (char)xem;
mnu.ShortcutKeyDisplayString = c.ToString();
Then you'll need to assign an eventhandler to the KeyDown event of your contextmenu. In the handler, you will be able to tell which key was pressed using the KeyEventArgs parameter
The itemclicked event of the contextual menu is already defined - I just need to dynamically assign shortcut key based on the integer (ASCII code) - 1 to 9 keys.
FROM INTEGER to Key
Last edited by arhicoc; September 26th, 2011 at 03:30 AM.
Your first questions was "how do I assign a shortcut key to my contextmenu?". There a several ways of doing this. The one you have apparently already chosen is well documented.
If your problem lies in dynamically assigning shortcut keys, you could simply add a few lines of code that chooses between Keys.D1, Keys.D2 and so forth.
Well does your keyboard have a key that says '10' ? Mine doesn't
How would the user be expected to use the shortcut? As soon as he/she hits '1' the first menu item would be selected and the menu would (or at least, should) disappear.
In that case, I don't see any way of reliably converting any integer into one of the Keys enumeration. You will simply need to create your own "converter" method, something along the lines of:
Code:
public Keys GetKey(int num)
{
Keys k = Keys.D1;
switch(num)
{
case 1:
k = Keys.D1;
case 2:
k = Keys.D2;
}
return k;
}
You should also consider that most regional keyboard will have different configurations of the keys you mentioned, and you might run into problems if the user's keyboard does not match your own.
Bookmarks