Home > Delphi > Storing TControlbar child positions

Storing TControlbar child positions

February 27, 2014 Leave a comment Go to comments

I have seen people ask about this since Windows XP was hot, so here (drumroll) is how you save the position of the bars inside a TControlbar control. And also a perfect example of how useful class helpers are 🙂

Controlbars are neat

Controlbars are neat

Just put the code inside it’s own unit, add a reference to the unit in your form – and voila “loadfromstream” and “savetostream” can be used to store the positions of child controls to a stream.

  TControlBarHelper = Class helper for TControlBar
  public
    Procedure SaveToStream(aStream:TStream);
    Procedure LoadFromStream(aStream:TStream);
  End;

procedure TControlBarHelper.LoadFromStream(aStream: TStream);
var
  x:  Integer;
  mReader:  TReader;
  mName:  String;
  mObj: TControl;
begin
  if aStream<>NIL then
  begin
    mReader:=TReader.Create(aStream,1024);
    try
      if mReader.ReadInteger=$BABE then
      Begin
        x:=mReader.ReadInteger;
        while x>0 do
        begin
          mName:=mReader.ReadString;
          mObj:=FindChildControl(mName);
          if mObj<>NIL then
          begin
            with mReader do
            Begin
              mObj.Left:=ReadInteger;
              mObj.Top:=ReadInteger;
              mObj.Width:=ReadInteger;
              mObj.Height:=ReadInteger;
            end;
          end;
          dec(x);
        end;
      end else
      Raise Exception.Create
      ('Failed to read controlbar, header not recognized error');
    finally
      mReader.Free;
    end;
  end else
  Raise Exception.Create
  ('Failed to load controlbar, source stream was NIL');
end;

procedure TControlBarHelper.SaveToStream(aStream: TStream);
var
  x:  Integer;
  mWriter:  TWriter;
begin
  if aStream<>NIL then
  begin
    mWriter:=TWriter.Create(aStream,1024);
    try
      mWriter.WriteInteger($BABE);
      mWriter.WriteInteger(self.ControlCount);
      for x:=0 to self.ControlCount-1 do
      Begin
        mWriter.WriteString(Controls[x].Name);
        mWriter.WriteInteger(Controls[x].Left);
        mWriter.WriteInteger(Controls[x].top);
        mWriter.WriteInteger(Controls[x].width);
        mWriter.WriteInteger(Controls[x].Height);
      end;
    finally
      mWriter.FlushBuffer;
      mWriter.Free;
    end;
  end else
  Raise Exception.Create
  ('Failed to store controlbar, target stream was NIL');
end;
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: