Mirror

Revert all controls on a TForm to design-time values when clicking on a button at runtime (Views: 705)


Problem/Question/Abstract:

Is it possible to reset the state of controls like TEdit.text, TCheckBox.Checked, etc. at runtime to their original design-time values without assigning the property values for each control again?

Answer:

If I understand you correctly you want all controls on the form to revert to the design-time values when the user clicks the a cancel button, for example. The generic way would be to reload the controls from the form resource. The main problem is that you have to delete all components on the form first or you get a load of errors since the component loading code really creates new instances of all components on the form.

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls,
    StdCtrls;

const
  UM_RELOADFORM = WM_USER + 321;

type
  TForm1 = class(TForm)
    Button1: TButton;
    CheckBox1: TCheckBox;
    CheckBox2: TCheckBox;
    CheckBox3: TCheckBox;
    RadioGroup1: TRadioGroup;
    RadioGroup2: TRadioGroup;
    CheckBox4: TCheckBox;
    CheckBox5: TCheckBox;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
    procedure UMReloadForm(var msg: TMessage); message UM_RELOADFORM;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.Button1Click(Sender: TObject);
begin
  {Delay action until button click code has finished executing}
  PostMessage(handle, UM_RELOADFORM, 0, 0);
end;

procedure TForm1.UMReloadForm(var msg: TMessage);
var
  i: Integer;
  rs: TResourceStream;
begin
  {Block form redrawing}
  Perform(WM_SETREDRAW, 0, 0);
  try
    {Delete all components on the form}
    for i := ComponentCount - 1 downto 0 do
      Components[i].Free;
    {Find the forms resource}
    rs := TResourceStream.Create(FindClassHInstance(TForm1), Classname, RT_RCDATA);
    try
      {Recreate components from the form resource}
      rs.ReadComponent(self);
    finally
      rs.free
    end;
  finally
    {Redisplay form}
    Perform(WM_SETREDRAW, 1, 0);
    Invalidate;
  end;
end;

end.

<< Back to main page