Setting Access Keys for a Windows Form

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:

  1. ToolStripMenuItem mnuFile = new ToolStripMenuItem();
  2. 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:

  1. Button btnOk = new Button();
  2. btnOk.Text = "&OK";
  3. 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:

  1. Label lblName = new Label();
  2. lblName.Text = "&Name";
  3. lblName.UseMnemonic = true;
  4. lblName.TabIndex = 0;
  5. TextBox txtName = new TextBox();
  6. 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.

Share and Enjoy:
  • Print
  • Digg
  • StumbleUpon
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • email
  • LinkedIn
  • Technorati