Following two functions and step by step instructions will take some of the mystery out of using the registry for simple purposes:
function LoadStringFromRegistry(
sKey, sItem, sDefVal : string )
: string;
var
reg : TRegIniFile;
begin
reg := TRegIniFile.Create( sKey );
Result := reg.ReadString(
'', sItem, sDefVal );
reg.Free;
end;
procedure SaveStringToRegistry(
sKey, sItem, sVal : string );
var
reg : TRegIniFile;
begin
reg := TRegIniFile.Create( sKey );
reg.WriteString(
'', sItem, sVal + #0 );
reg.Free;
end;
|
For example, let's say you want to save the last time your program was executed [using the Registry] and retrieve that value at the start of the program.
FormatDateTime( 'mm/dd/yyyy hh:nn:ss', Now ) |
HKEY_CURRENT_USER\Software\
MyCompanyName\MyProgramName
SaveStringToRegistry(
//
// our registry key
//
'Software'+
'\MyCompanyName\MyProgramName',
//
// parameter
//
'LastTime',
//
// value
//
FormatDateTime(
'mm/dd/yyyy hh:nn:ss', Now )
);
|
sLastTime :=
LoadStringFromRegistry(
'Software'+
'\MyCompanyName\MyProgramName',
'LastTime',
//
// default value
//
'First Time'
);
|
If the parameter "LastTime" can not be found at the specified registry key, LoadStringFromRegistry() will return "First Time."
Please note that if you have more than a few values to save and/or retrieve using the Registry, calling above functions over and over is not recommended. Rather, you should open the registry once, write/read all the information and then close the registry.
NOTE: The "Registry" unit must be listed in the "uses" section of your source code (uses Registry;) in order for Delphi to recognize the "TRegIniFile" object.