Make a context-sensitive AcceptButton in C#


You’ve probably seen applications, often on web sites, where the action that a form takes when you press Enter depends on the control that has focus at the time. For example, many login pages have a place for you to enter your user name and password if you have an account, or to enter other information if you want to create an account. If you type your user name and password and press Enter, you go to a login success or failure page. If you enter your name in the new account area, you go to a new account page.

A Windows Form’s AcceptButton property determines which button is triggered when you press Enter, but a form can have only one AcceptButton. This example uses the following code to change the AcceptButton depending on which control has the focus.

private void createGroupBox_Enter(object sender, EventArgs e)
    this.AcceptButton = createButton;

private void loadTableGroupBox_Enter(object sender, EventArgs e)
    this.AcceptButton = makeItemsButton;

private void createFindGroupBox_Enter(object sender, EventArgs e)
    this.AcceptButton = findButton;

When focus enters one of the form’s GroupBox controls, the corresponding Enter event handler sets the form’s AcceptButton property to whichever button is appropriate for that GroupBox. For example, when focus is in the Load Table GroupBox, the Enter key fires the Make Items button. When focus is in the Create/Find GroupBox, the Enter key fires the Find button.

If you look very closely at the picture, you’ll see that the form automatically highlights the AcceptButton by giving it a blue outline. (In Windows 11 with this set of window settings, anyway.) That means an alert user can tell which button is the AcceptButton at any given moment.

I wouldn’t necessarily use this technique for every program, but it can make the user’s life easier if they must perform a certain sequence of events many times as in this example where the user creates a table, populates it, and then searches for items in it.

[Essential Algorithms: A Practical Approach to Computer Algorithms]

Note: This program is taken from an algorithms book I wrote. The naming conventions don’t follow my usual style because publishers prefer the style that Microsoft uses, which I find harder to read. For more information on algorithms, see my book
Essential Algorithms: A Practical Approach to Computer Algorithms

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in controls, user interface and tagged , , , , , , , , , . Bookmark the permalink.