FontDialog Control
The Font Dialog control (System.Windows.Forms.FontDialog) is a handy control for selecting different kinds of font and font-related properties.
Using the Font Dialog, you can change the font type, style, size, color, add effects and specify character sets for the font. You can also preview the actual font. The following are some of the useful properties of the Font Dia control.
Properties | Description |
---|---|
Color | The selected color of the user. |
Font | The resulting font constructed using the font dialog. |
MaxSize | The maximum size the dialog can provide. |
MinSize | The minimum size the dialog can provide. |
ShowApply | Demonstrates whether to demonstrate the Apply catch. |
ShowColor | Demonstrates whether to demonstrate the Color choice. |
ShowEffects | Indicates whether to show the Effects option. |
Note that the Font Dialog hides the option to choose color by default. To allow the user to choose a color, set the value of the ShowColor property to true. You can then access the selected color via the Color property. The ShowApply property allows you to show the Apply button on the Font Dialog. You can then handle the Apply event to apply the changes to the target font while not closing the dialog itself.
Let’s look at a simple example of using the Font Dialog control. Create a form similar to the form shown below.
We will be changing the font of the text box depending on the constructed font using the FontDialog control. Drag a FontDialogcontrol to the form. Since the Font Dialog control is not a visual control, it will be located at the bottom portion of the Designer. Double click the button and use the code below for the event handler.
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = fontDialog1.ShowDialog();
if (result == DialogResult.OK)
{
textBox1.Font = fontDialog1.Font;
}
}
We first called the ShowDialog static method of the FontDialog control to show the actual dialog to the user. The user can now pick the different font properties and click OK. We check if the user presses the OK button by testing the value returned by the ShowDialogmethod. If the user presses OK then we change the font of the textbox to the one specified by the user.
Run the program and type any text inside the text box. Click the button to open up the Font Dialog and then choose the desired font. Click OK and the font of the text box will change.