2008. december 3., szerda

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


Problem/Question/Abstract:

How can I save the font settings of a control to registry? Saving name , size, etc. as string/int doesn't seem the best way ... (as far as I remember , I can't even save all font options this way)

Answer:

You can create a little component (needs 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 already with key open a


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


would save the streamed data to the registry,


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


would read it back. Mind the caret!

Nincsenek megjegyzések:

Megjegyzés küldése