How to generate a random color in HEX format with VB.NET

2 Answers

0 votes
Imports System

Class Program
    Private Shared Function GenerateRandomHexColor() As String
        Dim hexChars = "0123456789ABCDEF"
        Dim rand = New Random()
        Dim hex = ""

        For i As Integer = 0 To 6 - 1
            hex += hexChars(rand.[Next](16))
        Next

        Return hex
    End Function

    Public Shared Sub Main()
        Console.WriteLine($"Random HEX Color: #{GenerateRandomHexColor()}")
    End Sub
End Class



' run:
'
' Random HEX Color: #3121E4
'

 



answered Oct 9, 2025 by avibootz
0 votes
Imports System

Module Program

    '--------------------------------------------------------------
    ' Generate a random color in HEX format (#RRGGBB).
    ' This program demonstrates how numbers and bits are used
    ' to produce a valid 24‑bit color value.
    '--------------------------------------------------------------

    ''' <summary>
    ''' Create a 24‑bit random integer (0x000000–0xFFFFFF).
    ''' VB.NET's Random class produces integers efficiently.
    ''' </summary>
    Function RandomColorInt(rng As Random) As Integer
        ' 24 bits → values from 0 to 16,777,215 (0xFFFFFF)
        Return rng.Next(0, &H1000000)   ' &H1000000 = 2^24
    End Function

    ''' <summary>
    ''' Convert a 24‑bit integer into a hex color string.
    ''' The "X6" format specifier ensures exactly 6 hex digits.
    ''' </summary>
    Function IntToHexColor(value As Integer) As String
        Dim hex As String = value.ToString("X6")  ' Convert to 6‑digit hex
        Return "#" & hex
    End Function

    ''' <summary>
    ''' Produce a random hex color by combining the two functions.
    ''' </summary>
    Function GenerateRandomHexColor(rng As Random) As (Value As Integer, HexColor As String)
        Dim value As Integer = RandomColorInt(rng)     ' 24‑bit random number
        Dim hexColor As String = IntToHexColor(value)  ' Convert to #RRGGBB
	
        Return (value, hexColor)
    End Function

    Sub Main()
        Dim rng As New Random()
        Dim result = GenerateRandomHexColor(rng)

        Console.WriteLine("Random 24‑bit value: " & result.Value)
        Console.WriteLine("Hex color: " & result.HexColor)
    End Sub

End Module


' run:
'
' Random 24‑bit value: 7668809
' Hex color: #750449
'

 



answered Aug 22 by avibootz
...