ColorGrid (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This examples demonstrates how to use the TColorGrid component.

ColorGrid1 is a TColorGrid component.

edBackgroundColor and edForegroundColor are edit boxes that display the hexadecimal color codes of the background and foreground colors.

btnSetBackgroundColor and btnSetForegroundColor are buttons that set the foreground and background on the color grid to the values entered in the edBackgroundColor and edForegroundColor edit boxes, respectively.

The btnNoBackground and btnNoForeground buttons disable the background and foreground from the color grid.

The check box cbClickEnablesColor controls whether clicking the color grid after the background and foreground have been disabled re-enables them or not.

This example uses a HexStringToInt method, which converts a string that represents a number in hexadecimal to the corresponding integer. You can implement such a function yourself or find something similar on the Internet.

Code

procedure TForm4.btnSetForegroundClick(Sender: TObject);
begin
  { If the value entered in the background edit box exists in the color grid, }
  if ColorGrid1.ColorToIndex(HexStringToInt(edForegroundColor.Text)) <> -1 then
    { then change the foreground color. }
    ColorGrid1.ForegroundIndex := ColorGrid1.ColorToIndex
      (HexStringToInt(edForegroundColor.Text));
end;

procedure TForm4.btnSetBackgroundClick(Sender: TObject);
begin
  { If the value entered in the background edit box exists in the color grid,}
  if ColorGrid1.ColorToIndex(HexStringToInt(edBackgroundColor.Text)) <> -1 then
    { then change the background color.}
    ColorGrid1.BackgroundIndex := ColorGrid1.ColorToIndex
      (HexStringToInt(edBackgroundColor.Text));
end;

procedure TForm4.btnNoForegroundClick(Sender: TObject);
begin
  { Disable the foreground. }
  ColorGrid1.ForegroundEnabled := False;
  { Clear the edit box that contains the foreground color. }
  edForegroundColor.Clear;
end;

procedure TForm4.btnNoBackgroundClick(Sender: TObject);
begin
  { Disable the background. }
  ColorGrid1.BackgroundEnabled := False;
  { Clear the edit box that contains the background color. }
  edBackgroundColor.Clear;
end;

procedure TForm4.cbClickEnablesFBClick(Sender: TObject);
begin
  { If you click No Background/No Foreground and cbClickEnablesFB is unchecked,
    then clicking the color grid will no longer select the foreground or background. }
  ColorGrid1.ClickEnablesColor := cbClickEnablesFB.Checked;
end;

procedure TForm4.ColorGrid1Change(Sender: TObject);
begin
  ColorGrid1.SetFocus;
  { When the color grid changes, set the background and foreground hexadecimal
   color codes from the two edit boxes to the new values. }
  edBackgroundColor.Text := IntToHex(ColorGrid1.BackgroundColor, 6);
  edForegroundColor.Text := IntToHex(ColorGrid1.ForegroundColor, 6);
end;

Uses