ReadComponentResFile (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

The following code defines a component class (streamable class) and a persistent class (TContainedClass) that is the type of a property on the component class. When a button is clicked, an instance of the component class is created, saved to a file, deleted, and then loaded from the file. By setting a breakpoint on the property setter of the TContainedClass SomeData property, you can watch how the streaming system sets property values when it reads them from a file.

Code

class TContainedClass : public TPersistent
{
  private:
    int FSomeData;
    void __fastcall SetSomeData(int Value)
      {
        // Place a breakpoint here and notice how the data is streamed back.
	FSomeData = Value;
      }
  public:
    virtual __fastcall TContainedClass(void) : TPersistent()
      { FSomeData = 42; }
      // Only published properties are automatically streamed.
  __published:
    __property int SomeData = { read=FSomeData, write=SetSomeData };
};

class TStreamableClass : public TComponent
{
  private:
    TContainedClass* FContainedClass;
  __published:
    __property TContainedClass* ContainedClass = { read= FContainedClass, write=FContainedClass };
  public:
    virtual __fastcall TStreamableClass(TComponent* Owner) : TComponent(Owner)
      {
        FContainedClass = new TContainedClass();
      }

    virtual __fastcall ~TStreamableClass(void)
      {
        delete FContainedClass;
      }
};

void RegisterClassesWithStreamingSystem(void)
{
  // Make sure that, as part of the startup code, your streaming classes are registered
  // with the streaming system.
  #pragma startup RegisterClassesWithStreamingSystem

  Classes::RegisterClass(__classid(TContainedClass));
  Classes::RegisterClass(__classid(TStreamableClass));
}

void __fastcall TForm1::Button1Click(TObject *Sender)
{
  const String FileName = GetCurrentDir() + L"\\myres.res";

  TStreamableClass* AClassInstance;

  AClassInstance = new TStreamableClass(NULL);
  WriteComponentResFile(FileName, AClassInstance);
  delete AClassInstance;

  TComponent* temp = ReadComponentResFile(FileName, NULL);
  AClassInstance = static_cast<TStreamableClass*>(temp);
  Memo1->Lines->Add(L"TComponent has been written to the file " + FileName);
  delete AClassInstance;
}

Uses