Home » C# Basics » 09 - Windows Programming - 2
9

Windows common dialogs - FontDialog

Explains how to integrate the windows common task "font format dialog box" in our application.

The FontDialog control displays a dialog box to the user for selecting the font of the text.

  • Open the project. Drag the FontDilaog control from the Dialogs section of the Toolbox and drop it on the form. The control will be displayed in the control tray.
  • Select the control in the control tray by clicking on it and then open the properties window. Set the value of the ShowColor property to true. This will enable the font color option to be displayed in the dialog box.
  • Switch to the code view. Add the ChangeFont() method as shown here:
 void ChangeFont() { if (fontDialog1.ShowDialog() == DialogResult.OK)

{ txtInput.Font = fontDialog1.Font; txtInput.ForeColor = fontDialog1.Color; } }

The ShowDialog() method will display the font dialog box. If the user selects a font (and optionally, the color) and clicks the OK button, the selected font will be assigned to the Font property of the textbox (txtInput.Font), using the Font property of the FontDialog control (fontDialog1.Font) which refers to the font selected by the user.

Similarly, the font color selected by the user is referenced by the Color property of the FontDialog control (fontDialog1.Color) and it is assigned to the ForeColor property of the textbox (txtInput.ForeColor). This will change the color of the font.

Now we need to call this method from the click events of the Font menu option and the toolbar button. The code below is for the click event of the menu option but the same code is applied to the click event of the toolbar button:

 private void mnuOptionsFont_Click(object sender, EventArgs e) { ChangeFont(); }

Note that the text in the textbox control cannot retain the formatting. Hence, the formatting applied will be lost when the file is opened next time.

  • Save and run the project. Type some text or open a file. Click on the menu option or the toolbar button to display the font dialog box:

The selected font and color options will be applied to the text: