[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Use accelerators on labels and buttons in C#

[Use accelerators on labels and buttons in C#]

To place an accelerator on a menu item, you put an ampersand in front of the letter in the menu item's caption that you want to be the accelerator. At run time, the caption is displayed with the accelerator letter underlined. For example, you would set the File menu's caption to be &File at design time and it would display as File at run time. (Note that in some operating systems the accelerator isn't underlined until the user presses the Alt key.)

Most programmers know that you can place accelerators on menu items to let the user access them by pressing the Alt key. For example, pressing Alt+F opens the File menu in most applications. However, many programmers don't know that you can also use accelerators on labels and buttons.

If you place an accelerator on a label and the user triggers the accelerator, focus moves to the next control after the label that can have the focus. In the example program the Street label's S is an accelerator. If you press Alt+S, the input focus moves to the next control in the tab order, which is the Street text box.

If you place an accelerator on a button, the user can use the accelerator to immediately fire the button. If you press Alt+O while running the example program, the OK button immediately fires.

Note that if you press and release the Alt key by itself, the program moves into a sort of accelerator mode. All of the accelerators become visible and you can press accelerator keys such as F and S to trigger various accelerators without pressing Alt again. This lets you easily navigate menus but it makes using labels and buttons with accelerators a bit more confusing. For example, you could press Alt, S to move to the Street text box. You might then like to start typing a street address but the program is still in accelerator mode so it treats any keys that you press as accelerators. You need to press Alt again or Escape to end accelerator mode.

You can avoid accelerator mode if you press Alt and the accelerator key at the same time as in Alt+Z. Then focus moves to the appropriate control without starting accelerator mode.

To make using your programs easier, you can add accelerators to labels before text boxes as in this example and to buttons.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.