问题
I would like to know how to save the contents of a "variable" after program is closed and reopened.
for eg: iCount:=0; inc(iCount)=1;
when i close the program and reopen i want iCount to contain 1. Thank you.
回答1:
There are many ways to do this. You need to save the value somewhere: in a file, in the Windows registry, in the cloud, ...
File
Perhaps the easiest approach is to use an INI file. Try this:
Create a new VCL application.
Add a field
FMyNumber: Integer
to the main form.To the main form, add the following methods (and make sure to include
IniFiles
andIOUtils
in the implementation section'suses
list):function TForm1.GetSettingsFileName: TFileName; begin Result := TPath.GetHomePath + '\Fuzail\TestApp'; ForceDirectories(Result); Result := Result + '\settings.ini'; end; procedure TForm1.LoadSettings; var Ini: TMemIniFile; begin Ini := TMemIniFile.Create(GetSettingsFileName); try FMyNumber := Ini.ReadInteger('Settings', 'MyNumber', 0); finally Ini.Free; end; end; procedure TForm1.SaveSettings; var Ini: TMemIniFile; begin Ini := TMemIniFile.Create(GetSettingsFileName); try Ini.WriteInteger('Settings', 'MyNumber', FMyNumber); Ini.UpdateFile; finally Ini.Free; end; end;
Now make sure to call these when your application is starting and shutting down:
procedure TForm1.FormCreate(Sender: TObject); begin LoadSettings; end; procedure TForm1.FormDestroy(Sender: TObject); begin SaveSettings; end;
Now the value of
FMyNumber
is saved between the sessions!
Registry
Another common approach, probably, is to use the registry. Try this:
Create a new VCL application.
Add a field
FMyNumber: Integer
to the main form.To the main form, add the following methods (and make sure to include
Registry
in the implementation section'suses
list):procedure TForm1.LoadSettings; var Reg: TRegistry; begin Reg := TRegistry.Create; try Reg.RootKey := HKEY_CURRENT_USER; if Reg.OpenKey('\Software\Fuzail\TestApp', False) then try if Reg.ValueExists('MyNumber') then FMyNumber := Reg.ReadInteger('MyNumber') finally Reg.CloseKey; end; finally Reg.Free; end; end; procedure TForm1.SaveSettings; var Reg: TRegistry; begin Reg := TRegistry.Create; try Reg.RootKey := HKEY_CURRENT_USER; if Reg.OpenKey('\Software\Fuzail\TestApp', True) then try Reg.WriteInteger('MyNumber', FMyNumber); finally Reg.CloseKey; end; finally Reg.Free; end; end;
Now make sure to call these when your application is starting and shutting down:
procedure TForm1.FormCreate(Sender: TObject); begin LoadSettings; end; procedure TForm1.FormDestroy(Sender: TObject); begin SaveSettings; end;
Again the value of
FMyNumber
is saved between the sessions!
来源:https://stackoverflow.com/questions/62178705/saving-a-value-even-after-program-is-closed-and-reopened