TStreamReadBuffer (Object Pascal)

From Appmethod Code Examples
Jump to: navigation, search

Description

This example requires TListBox, TMemo, TRichEdit, and TButton controls placed on the form. The list box should contain one or more items. When the form becomes visible, click the button and the contents of the list box will be transferred to a stream and then to the rich edit control.

Code

procedure TForm1.Button1Click(Sender: TObject);
var
  TempStream : TMemoryStream;
begin
  TempStream := TMemoryStream.Create;
  ListBox1.Items.SaveToStream(TempStream);  // Write list box contents to the
                                            // stream.
  TempStream.Position := 0;      // Reset to the beginning of the stream.
//   RichEdit1.Lines.LoadFromStream( TempStream); // Load stream contents into rich
                                               // edit control.
  LoadFromStream(TempStream, RichEdit1.Lines, nil);
  TempStream.Free;
end;

procedure TForm1.LoadFromStream(Stream: TStream; myStrings: TStrings; Encoding: TEncoding);
var
  Size: Integer;
  Buffer: TBytes;
begin
  myStrings.BeginUpdate;
  try
    Size := Stream.Size - Stream.Position;
    SetLength(Buffer, Size);
    Stream.ReadBuffer(Pointer(Buffer)^, Size);

    Size := TEncoding.GetBufferEncoding(Buffer, Encoding);
    myStrings.Text := Encoding.GetString(Buffer, Size, Length(Buffer) - Size);
  finally
    myStrings.EndUpdate;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  ListBox1.Items.Add('Apples');
  ListBox1.Items.Add('Oranges');
  ListBox1.Items.Add('Pears');
end;

Uses