How to Use ColorDialog in C# Change Background of Form

You may familiar with ColorDialog for changing colors in different software like MS Word. Like this you can also use ColorDialog in C# to open color box and select different colors.



How to declare a ColorDialog:

You can add ColorDialog from your C# ‘Tool Box’.
Or type ColorDialog cd = new ColorDialog();
- Where cd is the name of your ColorDialog.

How to open ColorDialog:

Type type: cd.ShowDialog();
- Where cd is the name of your ColorDialog.

How to get selected color to your C# program:

DialogResult.OK is the selected color when you press OK button. Like this you can set what happen when your click on Cancel button in your ColorDialog.

C# code to change background color of your C# form using ColorDialog:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Listbox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            ColorDialog cd = new ColorDialog();
            if (cd.ShowDialog() == DialogResult.OK)
            {
                this.BackColor = cd.Color;
            }
        }

    }
}


Sample Output:

How to Use ColorDialog in C# Change Background of Form




No comments:

Post a Comment