Tuesday, March 1, 2011

Register yourself in the registry

If you're still using good old INI files in your 32bit Windows programs, well, it's time to switch! The new Windows Registry is faster and space conscious than old INI files.
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.
  • First, we have to get the current date and time as a string, so we can pass it to the SaveStringToRegistry() function:
FormatDateTime(
'mm/dd/yyyy hh:nn:ss', Now )
  • Now we have to come up with an unique Registry key (so that we can store our values in the Registry without overwriting someone else's information). Since we're storing our program specific information, we'll start with the Software key and append the name of our company (called MyCompanyName for example) and the name of our product (called MyProgramName for example). SaveStringToRegistry() will automatically append the key you pass to the HKEY_CURRENT_USER root key, which will give you the following final key:
HKEY_CURRENT_USER\Software\
MyCompanyName\MyProgramName

  • Finally, we're ready to make our call:
SaveStringToRegistry(
//
// our registry key
//
'Software'+
'\MyCompanyName\MyProgramName',

//
// parameter
//
'LastTime',

//
// value
//
FormatDateTime(
'mm/dd/yyyy hh:nn:ss', Now )
);
  • To retrieve the information you've saved, simply call:
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.

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Kang Iwan K-sev | Thank's for your visit To My Site - Ridwan Mulyana | Cibeureum