In one of my projects, I recently ran into issues when adding a function to read a value from registry. This wasn’t a normal value and was meant to detect for use for testing. I had placed the functionality during the loading of the application and when testing in RAD Studio 10.4.2 Sydney, it worked great during debugging and testing out of the IDE in the Virtual Machine I use for development.
After some tracking, I realized it was in my code reading the registry and not using the proper calls or try/except protection.
I am just doing a read of the registry value, so different calls should be used to help overcome any user privileges issues.
First off, be sure you have System.Win.Registry in your uses clause.
Now lets set up a function to return the value of the registry.
function ReadRegistryValue: integer
const
keyname = 'Software\Delphi.Rocks\MyApp';
value = 'Testing123';
var
Registry : TRegistry;
begin
result := 0; // Default value of zero returned in case of an issue
Registry := TRegistry.Create(KEY_READ); // Create the option with read only permissions
try
Registry.RootKey := HKEY_LOCAL_MACHINE; // Use the HKLM section
// Check to make sure key even exists
if Registry.KeyExists(keyname) then
begin
// Check to make sure value even exists
if Registrly.ValueExists(value) then
begin
try
result := Registry.ReadInteger(value); // Get the value from the DWord32 Registry entry
except
ShowMessage('There was a problem reading the registry');
end;
end;
end;
finally
Registry.Free;
end;
end;
Now with the new code, should the registry entry not be there, the application will get a zero value from the call and not cause any errors.
