C# Windows Forms ColorDialog Examples

Let us look at a simple C# Windows Forms ColorDialog example.

Example 1: ColorDialog

This example will comprise the following files:

  • ColorDialog.cs

Step 1: Create Project

  1. The first step is to create a C# Project.
  2. Go to FILE-->New-->Project to create a new project.

Step 2: Write Code

Write Code as follows:

*(a). ColorDialog.cs

Create a file named ColorDialog.cs

Create a button as an instance field:

  class Form1 : Form {
    private Button button = new Button();

The main entry point for the application.

    public static void Main() {
      Application.EnableVisualStyles();
      Application.Run(new Form1());
    }

Create our constructor:

    public Form1() {
 set button properties

```csharp
      button.Text = "Color...";
      button.Location = new System.Drawing.Point(10, 10);

Listen to our button click:

      button.Click += delegate (object sender, EventArgs e) {

Instantiate a ColorDialog object:

        ColorDialog colorDialog = new ColorDialog();

Here's how you obtain the selected color from a ColorDialog:

        colorDialog.Color = BackColor;
        if (colorDialog.ShowDialog() == DialogResult.OK)
          BackColor = colorDialog.Color;
      };

Set the title of the Form

      Text = "ColorDialog example";

Add the button to the Form:

      Controls.Add(button);

Here is the full code

using System;
using System.Windows.Forms;

namespace FolderBrowserDialogExample {
  class Form1 : Form {
    private Button button = new Button();
    public static void Main() {
      Application.EnableVisualStyles();
      Application.Run(new Form1());
    }

    public Form1() {
      button.Text = "Color...";
      button.Location = new System.Drawing.Point(10, 10);
      button.Click += delegate (object sender, EventArgs e) {
        ColorDialog colorDialog = new ColorDialog();
        colorDialog.Color = BackColor;
        if (colorDialog.ShowDialog() == DialogResult.OK)
          BackColor = colorDialog.Color;
      };
      Text = "ColorDialog example";
      Controls.Add(button);
    }

  }
}

Run

Simply copy the source code into your C# Project,Build and Run. Alternatively download the code using the links provided below, then open the .csproj project, build and run.

Reference

Download the code using the below links:

Number Link
1. Download Example
2. Follow code author

Related Posts