Get an RGB Colour from an OLE_COLOR

Sometimes you need to know the Red, Green and Blue values of a Visual Basic/COM OLE_COLOR, particularly if you are going to use the colour in an API function. This tip shows you how to correctly convert an OLE_COLOR type to a RGB value using the OleTranslateColor API call exposed by OLEPRO32.DLL. It works for all colours, whether they are RGB colours, system colours of the type &H80000000F (vbButtonFace) or palette-matching colours such as &H2EECC99.

Start a new project in VB. Add the following code to the project's form:

Private Declare Function OleTranslateColor Lib "OLEPRO32.DLL" _
    (ByVal OLE_COLOR As Long, ByVal HPALETTE As Long, _
    pccolorref As Long) As Long 
Private Const CLR_INVALID = -1 

Private Function TranslateColor(ByVal oClr As OLE_COLOR, _ 
                        Optional hPal As Long = 0) As Long 
    ' Convert Automation color to Windows color 
    If OleTranslateColor(oClr, hPal, TranslateColor) Then 
        TranslateColor = CLR_INVALID 
    End If 
End Function 

To test out the function, add a Combo box, a Label and a Text Box to the project's form. Set the style of the Combo box to 2 (Drop Down List) and then add the following code:

Private Sub Combo1_Click() 
Dim lRGB As Long 
    
    Label1.BackColor = Combo1.ItemData(Combo1.ListIndex) 
    lRGB = TranslateColor(Combo1.ItemData(Combo1.ListIndex)) 
    Text1.Text = "R=" & (lRGB And &HFF&) & _
        ",G=" & (lRGB And &HFF00&) \ &H100 & _
        ",B=" & (lRGB And &HFF0000) \ &H10000 

End Sub 

Private Sub Form_Load() 
Dim i As Long 
Dim sNum As String 
    For i = 1 To &H18&
        sNum = Hex$(i) 
        If Len(sNum) = 1 Then sNum = "0" & sNum 
        Combo1.AddItem "&H800000" & sNum 
        Combo1.ItemData(Combo1.NewIndex) = &H80000000 + i 
    Next i 
    Combo1.ListIndex = 0 
End Sub 

When you change the selected item in the combo box, the text box will be set to the R,G,B components of the colour.