Access keys are a useful addition to any forms project. Although not all users will choose to learn and use them, the users that do will thank you, especially those less able users that may have trouble or issues with using a mouse. Access keys can greatly speed up user productivity, and are a feature of all non-trivial production applications.
There are three ways to set up access keys for controls that are all related. The easiest one is specifically for ToolStripMenuItems. Simply use the ‘&’ character in the control’s Text property to indicate the access key. For example, the string “&File” would make the ‘F’ of ‘File’ the access key for that menu item. Holding Alt and F will activate that menu item, as long as it is visible. This is the only step needed for menu items. For example:
-
ToolStripMenuItem mnuFile = new ToolStripMenuItem();
-
mnuFile.Text = "&File";
Now onto other controls. There are two ways you can set access keys for other controls. The simplest can be used in the following circumstances: the control you wish to provide an access key for has a Text and a UseMnemonic property, and the control is capable of receiving focus. If the control fulfills those requirements, you can usually set the Text property as above, and make sure that UseMnemonic is set to true – it should be, true is the default for all controls to my knowledge. The Button control is the most obvious control that this is useful for. For example:
-
Button btnOk = new Button();
-
btnOk.Text = "&OK";
-
btnOk.UseMnemonic = true;
If your control doesn’t have a Text property and a UseMnemonic property, but is capable of receiving the user’s focus, you can use a Label control to set the access key for you. To do this, drag your control and a Label control to your form. Set the Label’s Text and UseMnemonic properties as above. The last step is to set the TabIndex property of the label to 1 less than the tab index of the control you want to use the access key for. For example:
-
Label lblName = new Label();
-
lblName.Text = "&Name";
-
lblName.UseMnemonic = true;
-
lblName.TabIndex = 0;
-
TextBox txtName = new TextBox();
-
txtName.TabIndex = 1;
Just a footnote. Access keys are different from shortcut keys. Access keys are always triggered with the Alt key, whereas shortcut keys are generally (not always) triggered by the Control key. You can set shortcut keys for menu items using the ShortcutKeys property. Shortcut keys will not work on top level menu items, but they will work on other menu items. In addition, forms can have an AcceptButton and a CancelButton. These are the buttons whose Click events are fired when the user presses Enter or Escape respectively. Both of these are seperate from the concept of access keys.