Edit

Share via


Add an access key shortcut to a control (Windows Forms .NET)

An access key is an underlined character in the text of a menu, menu item, or the label of a control such as a button. With an access key, the user can "click" a button by pressing the Alt key in combination with the predefined access key. For example, if a button runs a procedure to print a form, and therefore its Text property is set to "Print," adding an ampersand (&) before the letter "P" causes the letter "P" to be underlined in the button text at run time. The user can run the command associated with the button by pressing Alt.

Controls that cannot receive focus can't have access keys, except label controls.

Designer

In the Properties window of Visual Studio, set the Text property to a string that includes an ampersand (&) before the letter that will be the access key. For example, to set the letter "P" as the access key, enter &Print.

Properties dialog with text property selected and access key

Programmatic

Set the Text property to a string that includes an ampersand (&) before the letter that will be the shortcut.

' Set the letter "P" as an access key.
Button1.Text = "&Print"
// Set the letter "P" as an access key.
button1.Text = "&Print";

Use a label to focus a control

Even though a label cannot be focused, it has the ability to focus the next control in the tab order of the form. Each control is assigned a value to the TabIndex property, generally in ascending sequential order. When the access key is assigned to the Label.Text property, the next control in the sequential tab order is focused.

Using the example from the Programmatic section, if the button didn't have any text set, but instead presented an image of a printer, you could use a label to focus the button.

' Set the letter "P" as an access key.
Label1.Text = "&Print"
Label1.TabIndex = 9
Button1.TabIndex = 10
// Set the letter "P" as an access key.
label1.Text = "&Print";
label1.TabIndex = 9
button1.TabIndex = 10

Display an ampersand

When setting the text or caption of a control that interprets an ampersand (&) as an access key, use two consecutive ampersands (&&) to display a single ampersand. For example, the text of a button set to "Print && Close" displays in the caption of Print & Close:

' Set the letter "P" as an access key.
Button1.Text = "Print && Close"
// Set the letter "P" as an access key.
button1.Text = "Print && Close";

displaying an ampersand in a button

See also