Since many dialog boxes are terminated by clicking on a button, the .NET Framework makes this process even easier than shown in the previous examples.
The Button control implements the IButtonControl interface, which provides a DialogResult property. You can assign any valid DialogResult value to any button. The value of this DialogResult property must be one of the members of the same DialogResult enumeration used by the Form.DialogResult property, shown in Table 6-4. When a button in a modal dialog box is clicked, its DialogResult property is assigned to the dialog box. This has the effect of terminating the dialog box with that DialogResult value.
To demonstrate this idea, comment out the Click event handlers for the btnOK and btnCancel buttons in the ongoing example (dlg.cs for the C# version, dlg.vb for the VB.NET version).
If you run the application now, the only way to close the dialog box is by clicking on the Close button in the upper-right corner, clicking on Close in the system menu, or pressing Alt+F4. The OK and Cancel buttons will have no effect.
Display the dialog box in Design view, select each button in turn, and set the DialogResult property for the btnOK and btnCancel buttons to OK and Cancel, respectively, in the Properties window. Now when you run the application, it will behave exactly as it did originally, when the button-click event handlers were in place. However, you did not have to implement any event handlers.
Perhaps the two most common actions your user will perform with a dialog box are to either accept the dialog or cancel the dialog. Users expect to be able to press Enter to accept a dialog box, or Escape to cancel a dialog. If a control other than your designated accept or cancel button has focus, then pressing either key will not have the desired effect until the appropriate button has focus.
You can designate a button on the form to always respond to the Enter key by setting the form's AcceptButton property. Likewise, you can designate the form to always respond to the Escape key by setting the form's CancelButton property. The value of each property must be a Button or LinkLabel controli.e., a control that implements the IButtonControl interface.
You can set the AcceptButton or CancelButton properties of a dialog box in Visual Studio .NET by selecting the form, and then setting the appropriate property in the Properties window. Each property will have a drop-down in the Properties window that displays all the buttons or LinkLabels on the form. Select the button for each property to be the default accept or cancel button.
Windows Forms and the .NET Framework
Visual Studio .NET
Controls: The Base Class
Text and Fonts
Drawing and GDI+
Labels and Buttons
Other Basic Controls
TreeView and ListView
Date and Time Controls
Menus and Bars
Exceptions and Debugging
Configuration and Deployment