Recipe 9.3. Letting the User Select a Color


Problem

You need the user to select a specific color for drawing.

Solution

Sample code folder: Chapter 09\UserColorSelect

For simple color-selection needs, use the ColorDialog control. This dialog, shown in Figure 9-3, lets the user select any of the 16,777,216 24-bit colors available in Windows.

Figure 9-3. The color dialog, in "full open" mode


Discussion

Create a new Windows Forms application, and add the following controls to Form1:

  • A Label control named ColorName. Set its Text property to Not Selected.

  • A PictureBox control named ColorDisplay. Set its BorderStyle property to FixedSingle.

  • A Button control named ActChange. Set its Text property to Change….

  • A ColorDialog control named ColorSelector.

Add informational labels if desired. The form should look something like Figure 9-4.

Figure 9-4. The controls on the color selection sample form


Now add the following source code to the form's code template:

 Private Sub ActChange_Click(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles ActChange.Click    ' ----- Prompt to change the color.    ColorSelector.Color = ColorDisplay.BackColor    If (ColorSelector.ShowDialog() = _          Windows.Forms.DialogResult.OK) Then       ' ----- The user selected a color.       ColorDisplay.BackColor = ColorSelector.Color       If (ColorSelector.Color.IsNamedColor = True) Then          ' ----- Windows has a name for this color.          ColorName.Text = ColorSelector.Color.Name       Else          ColorName.Text = "R" & ColorSelector.Color.R & _             " G" & ColorSelector.Color.G & _             " B" & ColorSelector.Color.B       End If    End If End Sub 

Run the program, and click the Change button to access the dialog. The form will show the selected color, and either the name of the color (if known) or its red-green-blue (RGB) value.

The ColorDialog includes a few Boolean properties that let you control the availability of the "color mixer" portion of the form (the right half). The dialog does not include features that let the user indicate transparency or the "alpha" level of a color.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net