OK, well the program uses just three variables, one for each of the colour components. We'll call them, not surprisingly, Red, Green and Blue. They are, or course, integers and we will declare them in the General Declarations section:
Option Explicit
Dim Red As Integer
Dim Green As Integer
Dim Blue As Integer
Here's the code for the Change event of the Red scroll bar:
Private Sub hsbRed_Change()
Red = hsbRed.Value
txtRedValue.Text = Red
lblRed.BackColor = RGB(Red, 0, 0)
lblDisplay.BackColor = RGB(Red, Green, Blue)
End Sub
- enter the code and save your work
- run the program
When the user changes the value of the Red scroll bar, then, several things happen. Our variable, Red, takes on the value that the user sets - this happens in the first line of code:
Red = hsbRed.Value
Next, this value is assigned to the Text property of the text box using
txtRedValue.Text = Red
We want to use the small label called lblRed to show the red component so its BackColor property is assigned that value using
lblRed.BackColor = RGB(Red, 0, 0)
The function called RGB is part of Visual Basic and its job in life is to determine the value of the colour to be displayed. The green and blue components are both set to zero because we only want to show the red component here.
On the other hand, we must also update the larger label, lblDisplay, to show the overall colour which includes all three components. That is done using
lblDisplay.BackColor = RGB(Red, Green, Blue)
If you run the program, you'll come across the same problem as we had previously, inasmuch as when you hold and drag the thumb of the scroll bar, the display is only updated when you release it. The solution is straightforward, though, and involves copying the same four lines of code to the Scroll event of the scroll bar to get this
Private Sub hsbRed_Scroll()
Red = hsbRed.Value
txtRedValue.Text = Red
lblRed.BackColor = RGB(Red, 0, 0)
lblDisplay.BackColor = RGB(Red, Green, Blue)
End Sub
The Change events of the Green and Blue scroll bars are coded in a similar way:
Private Sub hsbGreen_Change()
Green = hsbGreen.Value
txtGreenValue.Text = Green
lblGreen.BackColor = RGB(0, Green, 0)
lblDisplay.BackColor = RGB(Red, Green, Blue)
End Sub
and
Private Sub hsbBlue_Change()
Blue = hsbBlue.Value
txtBlueValue.Text = Blue
lblBlue.BackColor = RGB(0, 0, Blue)
lblDisplay.BackColor = RGB(Red, Green, Blue)
End Sub
As before, you need to copy each of these to the corresponding Scroll events of the scroll bars.
- run the program and check that it works
It's always nice to add a touch of colour - now you know how to do it!
|