Simple VB.net Code for RGB Color Decoding

 

 

 

 

         

Shown below is a simple VB.net code for displaying a color given its RGB code in either decimal or hex. This VB.net program can accept the code in either numerical format, and takes care of converting one format to the other before displaying the corresponding color. For example, in the screenshot of the form below, the  input hex code ABCDEF displays the shade of blue shown in the color output box.

  

 

 

 

 

 

 

 

 

 

 

 

        

Public Class frmMain Inherits System.Windows.Forms.Form
          

Function dec2baseN(ByVal value, ByVal outBase) As String
'Converts base 10 to any base
    

Dim q 'quotient
     Dim r 'remainder
     Dim m 'denominator
     Dim y 'converted value
     m = outBase
     q = value
     Do
          r = q Mod m
          q = Int(q / m)

          If r >= 10 Then
               r = Chr(65 + (r - 10))
          End If
          y = y & CStr(r)
     Loop Until q = 0
     dec2baseN = StrReverse(y)
End Function


Function baseN2dec(ByVal value, ByVal inBase) As String
'Converts any base to base 10
     Dim strValue, i, x, y
     strValue = StrReverse(CStr(UCase(value)))
     For i = 0 To Len(strValue) - 1
          x = Mid(strValue, i + 1, 1)
          If Not IsNumeric(x) Then
               y = y + ((Asc(x) - 65) + 10) * (inBase ^ i)
          Else
               y = y + ((inBase ^ i) * CInt(x))
          End If
     Next
     baseN2dec = y
End Function

Private Sub txtR_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtR.TextChanged
     txtHexR.Text = dec2baseN(txtR.Text, 16)
End Sub

Private Sub txtG_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtG.TextChanged
     txtHexG.Text = dec2baseN(txtG.Text, 16)
End Sub

Private Sub txtB_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtB.TextChanged
     txtHexB.Text = dec2baseN(txtB.Text, 16)
End Sub

Private Sub txtHexR_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles    txtHexR.TextChanged
     txtR.Text = baseN2dec(txtHexR.Text, 16)
End Sub

Private Sub txtHexG_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtHexG.TextChanged
     txtG.Text = baseN2dec(txtHexG.Text, 16)
End Sub

Private Sub txtHexB_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtHexB.TextChanged
     txtB.Text = baseN2dec(txtHexB.Text, 16)
End Sub

Private Sub cmdDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDisplay.Click
     lblColor.BackColor = Color.FromArgb(Val(txtR.Text), Val(txtG.Text), Val(txtB.Text))
End Sub

  
End Class