Export (0) Print
Expand All

Showing a Color Palette with the ColorDialog Component

Visual Studio .NET 2003

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.

    ' Visual Basic
    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
    
    // C#
    private void button1_Click(object sender, System.EventArgs e)
    {
       if(colorDialog1.ShowDialog() == DialogResult.OK)
       {
          button1.BackColor = colorDialog1.Color;
       }
    }
    
    // C++
    private:
       System::Void button1_Click(System::Object *  sender, 
          System::EventArgs *  e)
       {
          if(colorDialog1->ShowDialog() == DialogResult::OK)
          {
             button1->BackColor = colorDialog1->Color;
          }
       }
    
    Visual C# and Visual C++ Note   Be sure that the necessary code to enable the event handler is present. In this case, it would be similar to the following:
    // C#
    this.button1.Click += new System.EventHandler(this.button1_Click);
    // C++
    this->button1->Click +=
    new System::EventHandler(this, button1_Click);

See Also

ColorDialog Component (Windows Forms) | ColorDialog Class

Show:
© 2014 Microsoft