TComponent与String的转换(得到控件的DFM格式的描述)

现看下面这两个方法,把一个TComponent做成String,再就是把String转成TComponent

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); // 字符流读取String
  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;

 

http://blog.sina.com.cn/s/blog_44fa172f0101is8p.html

posted @ 2015-11-26 20:50  findumars  Views(529)  Comments(0Edit  收藏  举报