Change the form's AcceptButton depending on which control has focus 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 log in 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 log in success or failure. If you enter your name, 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 GroupBoxes, 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 closely at the picture, you'll see that the form automatically highlights the AcceptButton by giving it a blue outline. (In Vista 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.

(This program is taken from a book about algorithms that I'm currently writing. The naming conventions don't follow my usual style because publishers prefer the style that Microsoft uses, which I find harder to read. I'll post information about the book when it is available.)



What did you think of this article?

  • No trackbacks exist for this post.
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.


 Email (will not be published)


Your comment is 0 characters limited to 3000 characters.