שתף באמצעות


How to create a random color for changing a background n vb.net

Question

Thursday, February 27, 2014 12:00 PM

How to create a random color for changing a background n vb.net

All replies (4)

Thursday, February 27, 2014 12:19 PM | 3 votes

Hi,

 You can use the Random class to pick 3 random numbers for the Red, Green, and Blue values and use the Color.FromArgb method to set the color.

Public Class Form1
    Dim rnd As New Random

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Me.BackColor = Color.FromArgb(255, rnd.Next(255), rnd.Next(255), rnd.Next(255))
    End Sub
End Class

 

PS. Please edit your thread and change it from a Discussion to a Question. Thanks.   :)


Friday, February 28, 2014 6:15 AM | 1 vote

How to create a random color for changing a background n vb.net

Option Strict On

Public Class Form1

    Dim ColorNames As New List(Of String)

    Dim ColorName As System.Type = GetType(System.Drawing.Color)
    Dim ColorPropInfo As System.Reflection.PropertyInfo() = ColorName.GetProperties()

    Dim Rand As New Random

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.CenterToScreen()
        For Each CPI As System.Reflection.PropertyInfo In ColorPropInfo
            If CPI.PropertyType.Name = "Color" And CPI.Name <> "Transparent" Then
                ColorNames.Add(CPI.Name)
            End If
        Next
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Me.BackColor = Color.FromName(ColorNames(Rand.Next(0, ColorNames.Count)))
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Me.BackColor = Color.FromArgb(Rand.Next(0, 256), Rand.Next(0, 256), Rand.Next(0, 256))
    End Sub

End Class

Please BEWARE that I have NO EXPERIENCE and NO EXPERTISE and probably onset of DEMENTIA which may affect my answers! Also, I've been told by an expert, that when you post an image it clutters up the thread and mysteriously, over time, the link to the image will somehow become "unstable" or something to that effect. :) I can only surmise that is due to Global Warming of the threads.


Friday, February 28, 2014 8:16 AM

Two answers are right and complete .


Friday, February 28, 2014 8:40 AM

If you are interested in one more solution:

Dim random_colour = Color.FromArgb(&HFF000000 Or rnd.Next(&HFFFFFF + 1))