In this article we will see how we can change the background color of windows form dynamically.
Introduction
Just few days back one of my friends told me that he want to change color in windows form dynamically for his post graduation project.We had a nice brainstorming session and then found the solution by checking the control of windows.Let us see the solution.
Objective
- Understanding color dialog
- Basic Color Picker and Custom Color Picker
- How to apply them to background of the form.
Using the code
- Create a New Windows Project
- Now drag and drop 2 buttons name them as Choose Basic Color and Choose Custom Color respectively.
- Now go to the Toolbox -> Dialog Section -> Drag and Drop a Color Dialog box and change the name property to cddialog.
The Windows form should look something like this.
Now go to the code behind write the code on the following button click event.
// Code behind
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 ColorSetter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnBasic_Click(object sender, EventArgs e)
{
// Opening the color dialog.The full open property is set to false and hence we can open basic color selection
cddialog.FullOpen = false;
if (cddialog.ShowDialog() != DialogResult.Cancel)
{
this.BackColor = cddialog.Color;
}
}
private void btnCustom_Click(object sender, EventArgs e)
{ // Opening the color dialog.The full open property is set to true and hence we can open custom color selection
cddialog.FullOpen = true;
if (cddialog.ShowDialog() != DialogResult.Cancel)
{
this.BackColor = cddialog.Color;
}
}
}
}
Color Dialog :-
Color dialog allows to choose color from basic color setting and custom color setting.
How to Open Basic Color Setting ?
In order to open the basic color setting you have to set the full open property of the colordialog box to false.Once
you set it to false it will open the basic color picker.
How to Custom Basic Color Setting ?
In order to open the basic color setting you have to set the full open property of the colordialog box to true.Once
you set it to true it will open the custom color picker.
Output 1 : Setting Basic Color
Output 2 : Setting Custom Color
Conclusion
This code can be useful for setting colors on forms when needed.
Reference