BCB中组件和文本相互转化的例子

有时需要将某个组件的当前状态(控件的属性值,并且属性对象类型继承自TPersistent,因为TPersisten have assignment and streaming capabilities (dfm format))保存到文件中,下次运行时候再从文件中读出组件的属性并生成组件,遇到这样的情况就需要用到下面几个函数。

AnsiString CToString(TComponent *c)
{
    //将组件转化为text
    TMemoryStream* ms;
    TStringStream* ss;
    ss = new TStringStream(" ");
    ms = new TMemoryStream;
    try
    {
        ms->WriteComponent(c);
        ms->Position = 0;
        ObjectBinaryToText(ms, ss);
        ss->Position = 0;
        return ss->DataString;
    }
    __finally
   {
    delete ms;
    delete ss;
    }
    return ss->DataString;
}
//---------------------------------------------------------------------------
void StringToComponent1(TComponent* Component,const AnsiString& Value)
{
    //将text转化为组件
    TStringStream* ss;
    TMemoryStream* ms;

    ss = new TStringStream(Value);
    try
    {
        ms = new TMemoryStream;
        try
        {
            ObjectTextToBinary(ss, ms);
            ms->Position = 0;
            ms->ReadComponent(Component);

           //Component = ms->ReadComponent(NULL); 转化后组件没有parent,不推荐使用
        }
        __finally
        {
            delete ms;
        }
    }
    __finally
    {
        delete ss;
    }
}
//---------------------------------------------------------------------------

使用范例:

1、保存组件到文本文件

 TStringList *myList = new TStringList();

//将AForm上的每一个控件转化为字符串,并加入myList

for (int j = 0; j < AForm->ControlCount; j++)

      myList->Add(CToString(AForm->Controls[j]));

myList->SaveToFile(fileName);

 delete myList;

2、从保存文本中读取组件信息生成组件

TStringList *OpenList = new TStringList();

TStringList *ComList = new TStringList();

OpenList->LoadFromFile(OpenDialog1->FileName);

  for (int i = 0; i < OpenList->Count; i++)
  {
     str_read = OpenList->Strings[i];

     if (str_read != "")
        OpList->Add(OpenList->Strings[i]);

    else
    {
      AnsiString str_opStart;
      str_opStart = ComList->Strings[0];
      if (str_opStart.Pos("TStaticText")>0)
     {
        TStaticText *st = new TStaticText(AForm);
        StringToComponent1(st, ComList->Text);
        AForm->InsertControl(st); //如果不是TWinControl,替换为com->Parent = AForm并添加在 StringToComponent1之前;
      }

     // else if  (str_opStart.Pos("TLabel")>0)....eg 诸如此类

     OpList->Clear();
    }

 }

  delete ComList;
  delete OpenList;

阅读更多
文章标签: delete null c
个人分类: BCB Sky
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭