How to save the font settings of a control to the registry #192

Question
How can I save the font settings of a control to registry?

You can create a little component (that does not need not be installed on the palette) that allows you to stream a fonts properties to a stream. The stream contents could then be saved to a binary key in the registry.

{ ... }
type
  TFontWrapper= class( TComponent )
private
  FFont: TFont;
  Constructor Create( aOwner: TComponent ); override;
  Destructor Destroy; override;
  Procedure SetFont( value: TFont );
published
  property Font: TFont read FFont write SetFont;
end;
 
{ TFontWrapper }
 
constructor TFontWrapper.Create(aOwner: TComponent);
begin
  inherited;
  FFont :=TFont.Create;
end;
 
destructor TFontWrapper.Destroy;
begin
  FFont.Free;
  inherited;
end;
 
procedure TFontWrapper.SetFont(value: TFont);
begin
  FFont.Assign( value );
end;
 
{ ms is a field of the form }
procedure TForm1.Button1Click(Sender: TObject);
var
  helper: TFontWrapper;
begin
  if not Assigned(ms) then
    ms:= TMemoryStream.Create
  else
    ms.Clear;
  helper := TFontWrapper.Create( nil );
  try
    helper.font := label1.font;
    ms.WriteComponent( helper );
  finally
    helper.free;
  end;
  label1.font.size := label1.font.size + 2;
end;
 
procedure TForm1.Button2Click(Sender: TObject);
var
  helper: TFontWrapper;
begin
  If not Assigned(ms) then Exit;
  ms.Position := 0;
  helper := TFontWrapper.Create( nil );
  try
    ms.ReadComponent( helper );
    label1.font := helper.font;
  finally
    helper.free;
  end;
end;

If reg is a TRegistry instance with an already open key then:

reg.WriteBinaryData( valuename, ms.Memory^, ms.Size );

would save the streamed data to the registry, and:

ms.size := reg.GetDatasize( valuename );
reg.ReadBinaryData( valuename, ms.Memory^, ms.Size );

would read it back. Mind the caret!

Original resource: The Delphi Pool
Author: Peter Below
Added: 2012/07/08
Last updated: 2012/07/08