This OnClick event handler adds the value specified in the ValueforKey edit box to the registry key specified by the NameofKey edit box. If the named key does not already exist, it creates one. (Note that if you don抰 want to give the user a choice, this could be accomplished more simply by setting the CanCreate parameter of the OpenKey call to true).
procedure TForm1.Button1Click(Sender: TObject);
var
Reg: TRegIniFile;
begin
if Length(NameofKey.Text) or Length(ValueforKey.Text) <=0 then
Showmessage('Either the key name or value is missing.')
else begin
Reg:=TRegIniFile.Create('MyApp');
try
Reg.RootKey:=HKey_Local_Machine; // Section to look for within the registry
if not Reg.OpenKey(NameofKey.Text,False) then
if MessageDlg('The specified key does not exist, create it?'
,Mtinformation,[mbYes,mbNo],0)=mryes then
begin
Reg.CreateKey(NameofKey.Text);
if not Reg.OpenKey(NameofKey.Text,False) then
ShowMessage('Error in Opening Created Key')
else
Reg.WriteString('Main Section','Value1',ValueForKey.Text);
end
else
Reg.WriteString('Main Section','Value1',ValueForKey.Text);
finally
unction GetRegistryValue(KeyName: string): string;
var
Registry: TRegistry;
begin
Registry := TRegistry.Create(KEY_READ);
try
Registry.RootKey = HKEY_LOCAL_MACHINE;
// False because we do not want to create it if it doesn't exist
Registry.OpenKey(KeyName, False);
Result := Registry.ReadString('VALUE1');
finally
Registry.Free;
end;
end;
The following example retrieves a value from a registry entry.
#include <Registry.hpp>
AnsiString GetRegistryValue(AnsiString KeyName)
{
AnsiString S;
TRegistry *Registry = new TRegistry;
try
{
Registry->RootKey = HKEY_LOCAL_MACHINE;
// false because we do not want to create it if it doesn’t exist
Registry->OpenKey(KeyName, false);
S = Registry->ReadString("VALUE1");
}
__finally
{
delete Registry;
}
return S;