I need a procedure that recreates a form.
The reason being is that I have forms with many different components. These component values (edit box text, checkbox checked or not, etc) are saved inside onhide and loaded again isnide onshow. This makes sure all user settings are retained between runs of the program.
The problem comes when they make a change (intentionally or otherwise) that leads to problems. I want to be able to "reset" the form back to the default settings when the application is first installed.
I can create a reset button that runs this code
FormName.free;
DeleteFile('FormNameSettings.ini');
FormName:=TFormName.Create(Application);
FormName.show;
That does what is required. The form is closed, clears the settings file (so states are not restored when it shows again) and then recreates the form. The form now has the original default settings.
My problem is trying to get that code into a function that I can call easily from multiple forms.
procedure ResetForm(form:tform;filename:string);
begin
form.free;
if fileexists(filename)=true then deletefile(filename);
<what goes here to recretae the form by the passed tform?>
end;
Can anyone help get that ResetForm procedure working? Latest Delphi 11.
CodePudding user response:
As you are changing the form instance and want to return the new instance, form must be a var parameter.
Then you need to save some information about the form for later use:
- the form class
- the owner of the form
- is the form currently showing
This allows you to recreate the form.
procedure ResetForm(var form: TForm; const filename: string);
begin
var formClass := TFormClass(form.ClassType);
var formOwner := form.Owner;
var formShowing := form.Showing;
form.free;
if fileexists(filename) = true then
deletefile(filename);
form := formClass.Create(formOwner);
if formShowing then
form.Show;
end;