How to use a ColorDialog Box in C#

This tutorial will show you how to use a ColorDialog Box in C#. The purpose of ColorDialog box on windows applications is that, it provides a selection of colors. And you can use the ColorDialog Box for various reasons such as letting the user set or change a color of an object or specifying the background color of a windows form application. The ColorDialog Box like as show below. d1 The figure above shows a list of colors, but if you want to have some customize or define your own color to be used. You can click the “Define Custom Colors” button. Then it will give you a design look like as shown below. d2 At this time, let’s create a new project in C# called “Color Dialog”. Then we will add one label and a button. This will look like as shown below. d3 Then we will add a ColorDialog Box from the Toolbox and drag it on the form. And this will look like as shown below. d4 What we are doing here is that, when the user click the button, it will show you the ColorDialog Box. Then when the user selects a specific color from a ColorDialog Box and the user click the OK button. The color of the label we added in the form will change based on the color selected by the user. To do this, double click the “Select Color” button and add the following code:
  1. private void button1_Click(object sender, EventArgs e)
  2. {
  3. colorDialog1.ShowDialog();
  4. label1.ForeColor = colorDialog1.Color;
  5. }
In our code above, we just simply call the ColorDialog Box when the user click the button. And we set the Forecolor of the Label based on the user selected color during the run time of the application.This time, you can now test the application by pressing the “F5” or start button. And here’s all the code used in this application.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  10. namespace WindowsFormsApplication1
  11. {
  12. public partial class Form1 : Form
  13. {
  14. public Form1()
  15. {
  16. InitializeComponent();
  17. }
  19. private void button1_Click(object sender, EventArgs e)
  20. {
  21. colorDialog1.ShowDialog();
  22. label1.ForeColor = colorDialog1.Color;
  23. }
  26. }
  27. }

Add new comment