TSimpleBox with Color + Caption

Perfect — let’s make Step 3 of our Lazarus custom component learning path.

We’ll extend our TSimpleBox so it:

TSimpleBox with Color + Caption

unit SimpleBox;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, Controls, Graphics;

type
  TSimpleBox = class(TGraphicControl)
  private
    FColor: TColor;         // box background color
    FCaption: string;       // text displayed in the box
    procedure SetColor(AValue: TColor);
    procedure SetCaption(AValue: string);
  protected
    procedure Paint; override;
  public
    constructor Create(AOwner: TComponent); override;
  published
    property Color: TColor read FColor write SetColor default clRed;
    property Caption: string read FCaption write SetCaption;
  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('Samples', [TSimpleBox]);
end;

constructor TSimpleBox.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  Width := 80;
  Height := 50;
  FColor := clRed;
  FCaption := 'Hello';
end;

procedure TSimpleBox.SetColor(AValue: TColor);
begin
  if FColor <> AValue then
  begin
    FColor := AValue;
    Invalidate; // trigger repaint
  end;
end;

procedure TSimpleBox.SetCaption(AValue: string);
begin
  if FCaption <> AValue then
  begin
    FCaption := AValue;
    Invalidate; // redraw with new text
  end;
end;

procedure TSimpleBox.Paint;
var
  TextRect: TRect;
begin
  // Draw background
  Canvas.Brush.Color := FColor;
  Canvas.FillRect(ClientRect);

  // Draw caption centered
  Canvas.Font.Color := clWhite;
  Canvas.Font.Size := 10;
  TextRect := ClientRect;
  DrawText(Canvas.Handle, PChar(FCaption), -1, TextRect,
           DT_CENTER or DT_VCENTER or DT_SINGLELINE);
end;

end.

What’s New in Step 3 Caption property

property Caption: string read FCaption write SetCaption; Works like the Color property, but stores a string.

Centered Text Drawing

We use DrawText from LCLIntf (automatically available in Lazarus) to center the text horizontally and vertically.

Flags:

DT_CENTER → center horizontally

DT_VCENTER → center vertically

DT_SINGLELINE → avoid wrapping

Invalidate after change

Ensures the control updates as soon as Caption or Color changes.

Teaching progression so far: