1 //If the user can change the background color of a component, 2 //make sure that the caption/text is displayed in a contrasting color. 3 //--------------------------------------------------------------------------- 4 5 #include <vcl.h> 6 #include <stdlib.h> 7 #pragma hdrstop 8 9 #include "Unit1.h" 10 //--------------------------------------------------------------------------- 11 #pragma package(smart_init) 12 #pragma resource "*.dfm" 13 TForm1 *Form1; 14 //--------------------------------------------------------------------------- 15 __fastcall TForm1::TForm1(TComponent* Owner) 16 : TForm(Owner) 17 { 18 } 19 TColor ContrastColor(TColor clBackground){ 20 21 RGBQUAD *Quad1 = (RGBQUAD *)&clBackground; 22 if (((Quad1->rgbRed * 0.3) + (Quad1->rgbGreen * 0.59) + 23 (Quad1->rgbBlue * 0.11)) > 127.5){ 24 return clBlack; 25 } 26 else{ 27 return clWhite; 28 } 29 } 30 31 //--------------------------------------------------------------------------- 32 33 void __fastcall TForm1::Button1Click(TObject *Sender) 34 { 35 Edit1->Color= random(255) << 16 + random(255) << 8 + random(255); 36 Edit1->Font->Color = ContrastColor(Edit1->Color); 37 38 } 39 //---------------------------------------------------------------------------