ComponentToString (Object Pascal)

From Appmethod Code Examples
Jump to: navigation, search

Description

This example shows how to use the built-in component streaming support to convert any component into a string and to convert that string back into a component.

Code

type
  TForm1 = class(TForm)
    Memo1: TMemo;
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
  MyScrollBar = class(TScrollBar)
  end;

var
  Form1: TForm1;
  ScrollBar1: MyScrollBar;
  
implementation

{$R *.dfm}

function ComponentToStringProc(Component: TComponent): string;
var
  BinStream:TMemoryStream;
  StrStream: TStringStream;
  s: string;
begin
  BinStream := TMemoryStream.Create;
  try
    StrStream := TStringStream.Create(s);
    try
      BinStream.WriteComponent(Component);
      BinStream.Seek(0, soFromBeginning);
      ObjectBinaryToText(BinStream, StrStream);
      StrStream.Seek(0, soFromBeginning);
      Result:= StrStream.DataString;
    finally
      StrStream.Free;
    end;
  finally
    BinStream.Free
  end;
end;

function StringToComponentProc(Value: string): TComponent;
var
  StrStream:TStringStream;
  BinStream: TMemoryStream;
begin
  StrStream := TStringStream.Create(Value);
  try
    BinStream := TMemoryStream.Create;
    try
      ObjectTextToBinary(StrStream, BinStream);
      BinStream.Seek(0, soFromBeginning);
      Result:= BinStream.ReadComponent(nil);
    finally
      BinStream.Free;
    end;
  finally
    StrStream.Free;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Memo1.Text:= ComponentToStringProc(ScrollBar1);
end;

// Edit the scrollbar parameters in the memo, click this
// button and see the scrollbar change.
procedure TForm1.Button2Click(Sender: TObject);
begin
  ScrollBar1.Free;
  ScrollBar1:= (StringToComponentProc(Memo1.Text) as MyScrollBar);
  ScrollBar1.Parent:= Form1;
  ScrollBar1.Visible:= TRUE;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  ScrollBar1:= MyScrollBar.Create(Form1);
  ScrollBar1.Parent:= Form1;
  ScrollBar1.Visible:= TRUE;
  ScrollBar1.Top:= 48;
  ScrollBar1.Left:= 250;
  ScrollBar1.Name:= 'Ricksbar';
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  ScrollBar1.Free;
end;

initialization

RegisterClass(MyScrollBar);

Uses

See Also