user3001101
user3001101

Reputation: 21

How can I save variable values across program close/reopen?

basically all I want to do is code my project so that it stores any saved variables for the next time the program is run. At the moment once I close and reopen the program it obviously resets any variables. Is there any simple way to do this (please bear in mind, i'm very new at programming

Il give you an example. If I have a simple program that when I press a button it adds 1 to a counter. Now next time I open that program and press the button again I want to add to the previous counter.

Thanks in advance

Upvotes: 1

Views: 1985

Answers (1)

Atanas Krachev
Atanas Krachev

Reputation: 102

You can have two simple routines that save and load from the registry like this:

uses   SysUtils, Registry;
...
function RegistryLoadString(const sKey, sItem, sDefVal: string ): string;
var
  reg: TRegIniFile;
begin
  reg := TRegIniFile.Create(sKey);
  try
    result := reg.ReadString('', sItem, sDefVal);
  finally
    reg.Free;
  end;
end;

procedure RegistrySaveString(const sKey, sItem, sVal: string);
var
  reg: TRegIniFile;
begin
  reg := TRegIniFile.Create(sKey);
  try
    reg.WriteString('', sItem, sVal + #0);
  finally
    reg.Free;
  end;
end;

On application load you can use them like this:

counter := StrToInt(RegistryLoadString( 'My program', 'counter', '0' ));

And on application exit you will save the counter like:

RegistrySaveString( 'My program', 'counter', IntToStr(counter) );

Upvotes: 3

Related Questions