首页  编辑  

保存控件导文件和从文件中读取控件

Tags: /超级猛料/VCL/Control.控件使用开发和第三方控件/控件使用技巧/   Date Created:

saving several controls to one single file?

{

-> Question:

How can I store some TRichEdit components and TEdit Components in a single file?

-> Answer:

Use a filestream and a reader or writer object.

These ease the tasks of writing strings to a binary stream and reading them back.

}

// Save routine

procedure SaveEditcontrols ( const FileName : string ; const Controls : array of TCustomEdit );

var

 fs                 : TFilestream ;

 writer             : TWriter ;

 i                 : Integer ;

 ss                 : TStringstream ;

begin

 fs := TFilestream . Create ( FileName , fmCreate );

  try

   writer := TWriter . Create ( fs , 4096 );

    try

      for i := Low ( Controls ) to High ( Controls ) do

        if Controls [ i ] is TCustomRichedit then

        begin

         ss := TStringstream . Create ( EmptyStr );

          try

            with TRichedit ( Controls [ i ]) do

            begin

             Plaintext := False ;

             Lines . SaveToStream ( ss );

            end ;

           writer . WriteString ( ss . Datastring );

          finally

           ss . Free ;

          end ;

        end

        else

         writer . WriteString ( Controls [ i ]. Text );

    finally

     writer . Free ;

    end ;

  finally

   fs . Free ;

  end ;

end ;

// Load routine

// Lade Routine

procedure LoadEditcontrols ( const FileName : string ; const Controls : array of TCustomEdit );

var

 fs                 : TFilestream ;

 reader             : Treader ;

 i                 : Integer ;

 ss                 : TStringstream ;

begin

 fs := TFilestream . Create ( FileName , fmOpenread or fmShareDenyWrite );

  try

   reader := Treader . Create ( fs , 4096 );

    try

      for i := Low ( Controls ) to High ( Controls ) do

        if Controls [ i ] is TCustomRichedit then

        begin

         ss := TStringstream . Create ( reader . ReadString );

          try

            with TRichedit ( Controls [ i ]) do

            begin

             Plaintext := False ;

             Lines . LoadfromStream ( ss );

            end ;

          finally

           ss . Free ;

          end ;

        end

        else

         Controls [ i ]. Text := reader . ReadString ;

    finally

     reader . Free ;

    end ;

  finally

   fs . Free ;

  end ;

end ;

// Example to store 2 TRichEdits and 3 Edit Controls to one file

// Beispiel, um  3 TRichEdits und 3 TEdit Controls in einer Datei zu speichern

procedure TForm1 . Button1Click ( Sender : TObject );

begin

 SaveEditControls ( 'C:\temp\temp.dat' ,

    [ richedit1 , richedit2 , edit1 , edit2 , edit3 ]);

end ;