INTRODUCTION
In this article, I am going to explain how to use a ColorDialog box in a Windows Forms app using Visual studio 2017.
STEP 1: Create a new 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 new WinForms project with a default form and you should see the Windows designer.
STEP 2: Drag and drop controls to the Form
Let's add a ColorDialog control to the form by dragging it from Toolbox and dropping it to the form. You will see a colorDialog1 is added to the form. This control is now available to you in the code behind.
ColorDialog box in Windows Forms is used to launch a popup that lets you select a control from the color pallette. Once the color is selected, you could use the color to apply it to other controls. The ColorDialog allows you to open a more complete color picker. If AllowFullOpen property is set to false, this option is disabled. Custom colors are present in the control box that were added by the use. You can also add your own colors there with code.
I change the Text property of button to Select Color.
STEP 3: Coding for Button Click Event
You can add a button click event handler by simply double clicking on the button control. On this button control click event hander, we launch the color dialog by calling its ShowDialog method and after that, we pick a color and that color us set as the background color of a Textbox using ColorDialog.Color property.
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
-
- private void button1_Click(object sender, EventArgs e)
- {
- colorDialog1.ShowDialog();
- textBox1.BackColor = colorDialog1.Color;
-
- }
- }
- }
STEP 4: Compile and run
Now simply compile and run the application.
Once you click on the Select Color button, the color dialog will open where you can select a color. Select a color and clock Ok, the selected color will be updated as the background color of the textbox.
Summary
ColorDialog control provides the necessary functionality of a visual color picker. In this basic article, you saw how to use a ColorDialog control to pick a color.