[C# Helper]
Index Books FAQ Contact About Rod
[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]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

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

Title: Display a font selection dialog with an Apply button in C#


Sometimes an application displays a font selection dialog that has an Apply button. If you click that button, the application shows what it would look like if you accept the dialog's current font. If you click OK, the dialog closes and the application uses the selected font. If you click Cancel, the application restores its original font.

To use the Apply button in your progams, set the FontDialog's ShowApply property to true to make it display the Apply button. Then catch the dialog's Apply event and apply the currently selected font. The following code shows how this example does that.

// Apply the font. private void fdFont_Apply(object sender, EventArgs e) { this.Font = fdFont.Font; }

This code simply sets the form's Font property equal to the dialog's Font property.

Display the dialog as usual, but if the user doesn't click OK, restore the original font in case the program is displaying a preview of the font when the user closes the dialog. The following code shows how the example program does this.

// Display the dialog. private void btnSelectFont_Click(object sender, EventArgs e) { // Save the original font. Font original_font = this.Font; // Initialize the dialog. fdFont.Font = this.Font; // Display the dialog and check the result. if (fdFont.ShowDialog() == DialogResult.OK) { // Apply the selected font. this.Font = fdFont.Font; } else { // Restore the original font. this.Font = original_font; } }

This code saves the original font in case it is needed later. It sets the font dialog's Font property to the form's current font and displays the dialog.

When the user closes the dialog by clicking either OK or Cancel, the form could be displaying any font. It may be displaying its original font, it may be displaying the dialog's current font, or it may be displaying a font the user tried out by clicking the Apply button before using the dialog to select another font.

If the user clicks OK, the code sets the form's font to the one currently selected by the dialog. If the user clicks Cancel, the code sets the form's font to its original value.

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

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