BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Programming
.NET 1.1+

The Font Selection Dialog Box

The .NET framework class library includes several common dialog boxes. These allow standard interactions with the user, such as font, file or colour selection or configuration for printing. This article describes the font selection dialog box.

Enabling the Apply Button

Many dialog boxes that you see in Microsoft Windows applications include an Apply button, in addition to OK and Cancel. The Apply button should perform the same action as OK, without closing the dialog box.

FontDialog includes an option to enable the Apply button. All that you need to do is set the ShowApply property to true. However, as the font selection dialog box is modal and the Apply button does not close it, you cannot detect the use of Apply from the ShowDialog method's return value. Instead, you must subscribe to the dialog box's Apply event.

The Apply event does not provide any event argument information. However, you can obtain the FontDialog instance that raised the event from the sender parameter. This must be cast to the correct type before reading the Font or Color properties.

The final sample code demonstrates the Apply button. In this case the Apply event calls the same private method as is executed when the OK button is clicked. Try running the program and using the Apply button. You should see that the label's font updates without the dialog box closing.

private void SelectFontButton_Click(object sender, EventArgs e)
{
    using (FontDialog dialog = new FontDialog())
    {
        dialog.ShowColor = true;
        dialog.Font = SampleLabel.Font;
        dialog.Color = SampleLabel.ForeColor;
        dialog.MaxSize = 100;
        dialog.MinSize = 20;
        dialog.ShowApply = true;

        dialog.Apply += FontDialog_Apply;

        if (dialog.ShowDialog() == DialogResult.OK)
        {
            SetFontFromDialogOptions(dialog);
        }
    }
}

private void SetFontFromDialogOptions(FontDialog dialog)
{
    SampleLabel.Font = dialog.Font;
    SampleLabel.ForeColor = dialog.Color;
}

private void FontDialog_Apply(object sender, EventArgs e)
{
    FontDialog dialog = sender as FontDialog;
    SetFontFromDialogOptions(dialog);
}
13 November 2013