Title: Use standard dialogs in C#
To use a standard dialog, first place the dialog on a form and set any properties that you want to customize. For example, you may want to set a file dialog's Filter property to let the user easily filter for specific kinds of files. You may also want to set CheckFileExists for the OpenFileDialog and OverwritePrompt or CreatePrompt for the SaveFileDialog. (Although the defaults for those properties are sensible so you probably don't need to set them yourself.)
You can also create the dialogs in code at run time instead of placing them on a form. That saves a little memory because the dialogs don't exist when you're not using them, but using a form is generally more convenient.
Using a dialog at run time is a three step process.
- Initialize the dialog. Set dialog's properties to show the current settings. For example, set a FontDialog's Font property to the current font.
- Display the dialog and check the return result. Call the dialog's ShowDialog method and see if it returns OK, indicating that the user clicked the OK, Save, Open, or other button that makes a selection. (Basically the button that's not Cancel.)
- If the user clicked OK (or whatever's appropriate for that kind of dialog), use the dialog's values to do something. For example, make the form use the font selected in a FontDialog.
The example program lets the user select a file for opening, a file for saving, foreground and background colors, and a font. The following code shows how the program handles font selection.
// Select the font.
private void btnFont_Click(object sender, EventArgs e)
{
// Initialize.
fdFont.Font = this.Font;
// Display and check result.
if (fdFont.ShowDialog() == DialogResult.OK)
{
// Take action.
this.Font = fdFont.Font;
}
}
This code performs the three steps described above: initialize, call ShowDialog and check the result, do something with the user's selection.
The code for the other dialogs follows the same steps, although the details are different.
Download the example to experiment with it and to see additional details.
|