Visual Basic System Services
OleTranslateColor: Inverting RGB and System Colors
Posted:   Friday July 26, 2002
Updated:   Monday December 26, 2011
Applies to:   VB4-32, VB5, VB6
Developed with:   VB6, Windows XP
OS restrictions:   None.
Author:   VBnet - Randy Birch


OleTranslateColor: Translate System/RGB Colours into R, G and B Components

Here's a quick routine that when passed a RGB value or a OLE system colour will return the inverse of the colour passed.  The method uses OleTranslateColor() to convert to RGB the colour passed, if required, then flips the colour by OR'ing it with &HFFFFFF (decimal 16777215).  The result is the bitwise opposite of the colour passed which could be used to provide a contrasting background for a given text colour, as shown.
 BAS Module Code

 Form Code
To a form, add a label (Label1), command button (Command1), a common dialog control (CommonDialog1), and two picture boxes (Picture1, Picture2). Other labels are optional. Add the following code:

Option Explicit
' Copyright 1996-2011 VBnet/Randy Birch, All Rights Reserved.
' Some pages may also contain other copyrights by the author.
' Distribution: You can freely use this code in your own
'               applications, but you may not reproduce 
'               or publish this code on any web site,
'               online service, or distribute as source 
'               on any media without express permission.
Private Declare Function OleTranslateColor Lib "olepro32.dll" _
  (ByVal OLE_COLOR As Long, _
   ByVal HPALETTE As Long, _
   pccolorref As Long) As Long

Private Sub Form_Load()

   With Command1
      .Caption = "Select Colour"
   End With
   With Label1
      .AutoSize = True
       .Caption = ""
      .WordWrap = True
      .Move 200, 200, Form1.ScaleWidth - 400
      .Caption = "Select any colour from the common " & _
               "colour dialog. This label background " & _
               "and left picturebox will take on the " & _
               "selected colour, while the label's text " & _
               "and right picturebox will display " & _
               "the inverse of the selection."
      .AutoSize = True
   End With
End Sub

Private Sub Command1_Click()

   With CommonDialog1
      Label1.BackColor = .Color
      Label1.ForeColor = InverseRGB(.Color)
      Picture1.BackColor = .Color
      Picture2.BackColor = InverseRGB(.Color)
   End With
End Sub

Public Function InverseRGB(ByVal col As Long) As Long
   Const Inverse As Long = &HFFFFFF
   InverseRGB = GetClrrefFromOLEColour(col) Xor Inverse
End Function

Private Function GetClrrefFromOLEColour(ByVal dwOleColour As Long) As Long
  'pass a colour, and return the colour
  'with the system bit stripped if present
   OleTranslateColor dwOleColour, 0, GetClrrefFromOLEColour
End Function


PayPal Link
Make payments with PayPal - it's fast, free and secure!


Copyright 1996-2011 VBnet and Randy Birch. All Rights Reserved.
Terms of Use  |  Your Privacy


Hit Counter