Functions inside Function

Next we will create random colors by using the Rnd function as the argument inside the FromArgb function.

Add a button called BtnRandomColor to your project. Make the text of the button "Random Color." (Remember, you can not have any spaces inside the name of the button, but you can use spaces in the text.)

Write the code as shown below:

Private Sub BtnRandomColor_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
     Handles BtnRandomColor.Click
  Me.BackColor = Color.FromArgb(Rnd() * 255, Rnd() * 255, Rnd() * 255)
End Sub

The asterisk, *, is used for multiplication. The Rnd function returns a value that is greater than or equal to 0, and less than 1. To get random values that are between 0 and 255 we can multiply the random value by 255. We use Rnd( ) * 255 for each of the three arguments as the values for red, green, and blue.

Run the program and click the button several times. You will get a different color each time you click. (With 255 possible values for red * 255 possible values for green * 255 possible values for blue, there are over 16 million possible colors, so it is fairly safe to make that statement! )

Randomize

If you run the program several times, you will get the same sequence of colors each time. This can be very useful: if something goes wrong, it makes it easy to repeat the condition that caused the error. It can also make it easier to win at a game of dice, but it isn't very interesting. To make the program give you new values each time, add the following code to the Load even of Form1, (Select Form1 events as the object, Load as the event in the drop-down  boxes at the top of the code view window.)

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
   Randomize()
End Sub

INDEX, Built in Functions and Constants, Functions, Random Numbers, How Random Numbers Work, RGB Colors, Random Colors
Next lesson: Visual Basic Calculations

Copyright © Zebra0.com
All rights reserved worldwide.

 
 

Random Colors