unit SwitchButton;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls;

type
  TSwitchButton = class(TCustomControl)
  private
  private
    FBitmap: TBitmap;
    FSwitchOn: boolean;
    FOnChanged: TNotifyEvent;
    FClickEnabled: boolean;
    procedure SetBitmap(const Value: TBitmap);
    procedure SetSwitchOn(const Value: boolean);
  protected
    procedure Paint; override;
    procedure Click; override;
    procedure SetEnabled(Value: boolean); override;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  published
    property Align;
    property Enabled;
    property ShowHint;
    property Visible;

    property Bitmap : TBitmap read FBitmap write SetBitmap;
    property ClickEnabled : boolean read FClickEnabled write FClickEnabled;
    property SwitchOn : boolean read FSwitchOn write SetSwitchOn;
    property OnChanged : TNotifyEvent read FOnChanged write FOnChanged;
  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('RyuLib', [TSwitchButton]);
end;

{ TSwitchButton }

procedure TSwitchButton.Click;
begin
  inherited;

  if (FClickEnabled = false) or (Enabled = false) then Exit;

  SwitchOn := not SwitchOn;
  if Assigned(FOnChanged) then FOnChanged(Self);
end;

constructor TSwitchButton.Create(AOwner: TComponent);
begin
  inherited;

  FClickEnabled := true;
  FBitmap := TBitmap.Create;
end;

destructor TSwitchButton.Destroy;
begin
  FreeAndNil(FBitmap);

  inherited;
end;

procedure TSwitchButton.Paint;
var
  SrcRect : TRect;
begin
  inherited;

  if FBitmap.Width * FBitmap.Height = 0 then Exit;

  if csDesigning in ComponentState then
    with inherited Canvas do begin
      Pen.Style := psDash;
      Brush.Style := bsClear;
      Rectangle(0, 0, Width, Height);
    end;

  if Enabled = false then
    SrcRect := Rect(Width*2, 0, Width*3, Height)
  else begin
    if FSwitchOn then
      SrcRect := Rect(0, 0, Width, Height)
    else
      SrcRect := Rect(Width, 0, Width*2, Height);
  end;

  Canvas.CopyRect(Rect(0, 0, Width, Height), FBitmap.Canvas, SrcRect);
end;

procedure TSwitchButton.SetBitmap(const Value: TBitmap);
begin
  FBitmap.Assign(Value);

  Height := Value.Height;
  Width := Value.Width div 3;

  Invalidate;
end;

procedure TSwitchButton.SetEnabled(Value: boolean);
begin
  inherited;

  Invalidate;
end;

procedure TSwitchButton.SetSwitchOn(const Value: boolean);
begin
  FSwitchOn := Value;
  Invalidate;
end;

end.
