ColorDialog Control
The Color Dialog (System.Windows.Forms.ColorDialog) is used when you want to pick different colors. For example, when you want to pick a color of the font or a background color for the form, you can use the Color Dialog control.
The following ar a number of the helpful properties of the Color Dialog control.
Properties | Description |
---|---|
AllowFullOpen | Determines whether the client can pick custom hues. |
Color | The color that the user selected. |
CustomColors | Determines whether the client can pick custom hues. |
FullOpen | Indicates whether the part used to pick custom hues are naturally open. |
The window of the initially composed of predefined color palettes. You can click the Define Custom Colors button to reveal a more colors where you can pick every color you can think of. You can even provide the Hue, Saturation, Luminance values or RGB values. The main window allows you to choose colors while the right slider adjusts the brightness of the color. You can click the Add Custom Colors button to put the selected color to the Custom Colors palette so you can reuse it later.
The following example demonstrates the use of the ColorDialog. Create a similar form shown below.
Drag a Color Dialog control to the form. It will not be visible to the form, but you can find it a the bottom section of the Designer.
To change properties of the Color Dialog control, click it in the designer and proceed to Properties Window.
Double-click the button to create an event handler for its Click event. Use the following code for the event handler.
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = colorDialog1.ShowDialog();
if (result == DialogResult.OK)
{
this.BackColor = colorDialog1.Color;
}
}
The first line of code calls the Color Dialog‘s ShowDialog static method. This method shows up the color dialog where the user can pick a color. This method returns a System.Windows.Forms.DialogResult value which indicates whether the user clicked the OK or the Cancel button of the Dialog. If the user clicked a color and pressed the OK button, the dialog will close and the color that the user picked are stored in the Color property of the control. We test the value of the result to determine if the user clicks the OK button. If so, we changed the background color of the form to the color the user picked using the value of the Color property.
Run the program and click the button. The Color dialog will open up. Select a color and click OK. Watch as the color of the form changes to the color you have picked.