Share via


How to: Show a Color Palette with the ColorDialog Component

The ColorDialog component displays a palette of colors and returns a property containing the color the user has selected.

To choose a color using the ColorDialog component

  1. Display the dialog box using the ShowDialog method.

  2. Use the DialogResult property to determine how the dialog box was closed.

  3. Use the Color property of the ColorDialog component to set the chosen color.

    In the example below, the Button control's Click event handler opens a ColorDialog component. When a color is chosen and the user clicks OK, the Button control's background color is set to the chosen color. The example assumes your form has a Button control and a ColorDialog component.

    Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click
       If ColorDialog1.ShowDialog() = DialogResult.OK Then
          Button1.BackColor = ColorDialog1.Color
       End If
    End Sub
    
    private void button1_Click(object sender, System.EventArgs e)
    {
       if(colorDialog1.ShowDialog() == DialogResult.OK)
       {
          button1.BackColor = colorDialog1.Color;
       }
    }
    
    private void button1_Click(Object sender, System.EventArgs e)
    {
       if (colorDialog1.ShowDialog() == DialogResult.OK)
       {
          button1.set_BackColor(colorDialog1.get_Color());
       }
    }
    
    private:
       void button1_Click(System::Object ^ sender, 
          System::EventArgs ^ e)
       {
          if(colorDialog1->ShowDialog() == DialogResult::OK)
          {
             button1->BackColor = colorDialog1->Color;
          }
       }
    

    (Visual C#, Visual C++) Place the following code in the form's constructor to register the event handler.

    this.button1.Click += new System.EventHandler(this.button1_Click);
    
    this.button1.add_Click(new System.EventHandler(this.button1_Click));
    
    this->button1->Click += 
       gcnew System::EventHandler(this, &Form1::button1_Click);
    

See Also

Reference

ColorDialog Class

Other Resources

ColorDialog Component (Windows Forms)