Author: Jonas Bilinkevicius
In D6, what's the best or usual way to stream an object to text so that it shows up
just as it does when you copy an object to the clipboard or when you display a form
as text?
Answer:
This example shows how to use the built-in VCL component streaming support to
convert any component into a string and convert that string back into a component.
1 2 function ComponentToString(Component: TComponent): string;
3 var4 BinStream: TMemoryStream;
5 StrStream: TStringStream;
6 s: string;
7 begin8 BinStream := TMemoryStream.Create;
9 try10 StrStream := TStringStream.Create(s);
11 try12 BinStream.WriteComponent(Component);
13 BinStream.Seek(0, soFromBeginning);
14 ObjectBinaryToText(BinStream, StrStream);
15 StrStream.Seek(0, soFromBeginning);
16 Result := StrStream.DataString;
17 finally18 StrStream.Free;
19 end;
20 finally21 BinStream.Free
22 end;
23 end;
24 25 function StringToComponent(Value: string): TComponent;
26 var27 StrStream: TStringStream;
28 BinStream: TMemoryStream;
29 begin30 StrStream := TStringStream.Create(Value);
31 try32 BinStream := TMemoryStream.Create;
33 try34 ObjectTextToBinary(StrStream, BinStream);
35 BinStream.Seek(0, soFromBeginning);
36 Result := BinStream.ReadComponent(nil);
37 finally38 BinStream.Free;
39 end;
40 finally41 StrStream.Free;
42 end;
43 end;