Windows common dialogs - ColorDialog
Explains how to integrate the windows common task "color dialog box" in our application.
The ColorDialog control is used to display a dialog box that allows the user to select a color. Apart from the available basic colors, the user can create custom colors also. We will use this control to change the background color of the typing area (the textbox control) in the application.
- Open the project. Drag the ColorDialog control from the Dialogs section in the Toolbox and drop it on the form. The control will be displayed in the control tray area. The name of the control is colorDialog1. We can change this name in the properties window but for this example, we are going to use the default name.
- Switch to the code view in the IDE and define a method - ChangeBackColor() - as shown below:
void ChangeBackColor() { if (colorDialog1.ShowDialog() == DialogResult.OK) { txtInput.BackColor = colorDialog1.Color; } }
The ShowDialog() method will display the color dialog box. If the user selects a color and clicks the OK button, the `if' condition becomes true. The color selected by the user is referenced by the colorDialog1.Color property. This color is then assigned to the BackColor property of the textbox `txtInput'.
- We can now call the ChangeBackColor() method from the click events of the related menu option and toolbar button as shown here:
private void mnuOptionsBackground_Click(object sender, EventArgs e) { ChangeBackColor(); }
- Save and run the application. Open a file and then click the menu option or toolbar button to change the background color:
We can select a basic color or we can define a custom color. When we click the OK button, the selected color is applied to the background:
We have written code for all of the menu options related to file handling. However, we need the code for the `New' menu option (to create a new file) and the `Exit' menu option (to close the application). For a new file, we can create a method that will simply clear the contents of the textbox and then call this method from the click events of the `New' menu option and toolbar button:
void NewFile() { txtInput.Clear(); }
For the Exit menu option, the following code is used to exit the application:
private void mnuFileExit_Click(object sender, EventArgs e) { Application.Exit(); }
The Exit() method of the Application class closes the running application.
In this lesson, we have learned how to design menu bars and toolbars and work with files using windows common dialogs. In the next lesson, we will cover another important aspect of C# programming - Data Access.

