INTRODUCTION
In this article, I am going to explain how to use a FontDialog box in a Windows Forms app using Visual studio 2017.
STEP 1: Start the Project
Let's create a new project using Visual Studio 2017.
Select New Project--->Visual C#-->Windows Forms App (.NET Framework), give your project a name and click OK.
This action creates a WinForms project with a default form and you should see the Windows designer.
STEP 2: Drag and Drop Control
Let's add a FontDialog control to the form by dragging it from Toolbox and dropping it to the form. You will see a FontDialog 1 is added to the form. This control is now availabe to you in the code behind.
FontDialog Control
FontDialog represents a common dialog box that displays a list of fonts that are currently installed on system. The FontDialog box allow the user to choose attributes like logical font, font style, point size, effects and Scripts. FontDialog presents a Font selection dialog box that allows the user to select a font from the list of installed fonts. By the FontDialog control, we can quickly add an ability for users to select their favorite fonts.
Show FontDialog
Now, let's add a other control to the form by dragging a other control from Toolbox to the form. You may also want to change the properties of the other controls.
Let's add a Label and a Button control to the form. We will launch Font Dialog on click on the button, select a font, and the selected font will be the font of the Label control.
Change the text of button and Label controls to what you like.
STEP 3: Coding for Button Click Event
You can add a button click event handler by simply double clicking on the buttoon control. On this button control event handler, we can change the font of the text displayed in label.
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
-
- private void button1_Click(object sender, EventArgs e)
- {
- DialogResult fontResult = fontDialog1.ShowDialog();
- if (fontResult == DialogResult.OK)
- {
- label1.Font = fontDialog1.Font;
- }
- }
- }
STEP 4: Compile and Run
Now simply compile and run the aplication.
Once you click on the Change the Font button, the font dialog will open where you can select a font. Select a font and click Ok, the selected font will be updated as the font of the text in the label.
Summary
In this basic article, you saw how to use a FontDialog control to choose a font. Hope you found this article intresting. For any feedback, please post it as a comment at the bottom of this article. Thank you!