Highlights
All Snippets
Top 100 Snippets
Librarians
gbCodeLib

By Language
VB6
JavaScript
Perl
HTML
SQL
Java
DOS

GBIC >> Source Code >> Visual Basic >> Snippet

Convert between Long, RGB, VB, and Web colors


'in VB, a long integer representing color is created from RGB values:
Color = B   *  &FF00&     +   G   * &HFF&    +   R
'or this without Hex notation
Color = (256 * 256 * B)   + G * 256 + R

'the bult-in VB function RGB can calculate the Long value for you
Color = RGB (R,G,B)

'to get the RGB from a long
Function Color_to_RGB (Color As Long , R As Integer , G As Integer , B As Integer ) As Long
  R = Color And &HFF&                                     
  G = (Color And &HFF00&) \ &H100&               
  B = (Color & And &HFF0000) \ &H10000          
   'or
  R = Color Mod 256
  G = (Color \ 256 ) Mod 256
  B = (Color \ 256 \ 256 ) Mod 256
End Function

'in VB colors > &H80000000 are systems colors - which must be
'interpreted by VB - they are not standard Long color values!
'use the GetSysColor API to return the true long value of a system color
Private Declare GetSysColor Lib "user32" ( ByVal nIndex As Long ) As Long
iColor = GetSysColor (iColor And &HFFFFFF)

'values of R, G, B can be used to  as BBGGRR to form a hex representation of a color that VB understands
'so, for R = "F0",  G="A3, and B = "2F, the hex representation in VB becomes BBGGRR:
&H2FA3F0

'to get the VB hex string for a color from the Long or RGB
VBColorHexString = Right$( "000000" & Hex $( Color), 6)
VBColorHexString = Right$( "000000" & Hex $( R + 256 * (G + 256 * B ), 6)

'Note:  The Internet and other applications use RRGGBB for the hex format of a color
WebColorHexString = Right$( "000000" & Hex $( B + 256 * (G + 256 * R ), 6)

'to get the Web hex color string from the VB hex color string, swap the first 2 and last 2 character strings
WebColorHexString = Right$(VBHexColorString, 2) & Mid $(VBColorHexString, 3, 2) & Left$(VBHexColorString, 2)