First off, you can't use the parameter-less overload of RaiseLastOSError()
with TRegistry
, because the Registry API doesn't report errors via the Win32 GetLastError()
function. Registry API functions return error codes directly to the caller. TRegistry
captures those error codes in its LastError
property, which you can then pass to one of the other overloads of RaiseLastOSError()
, eg:
if not Registry.OpenKey(KeyLocation, True) then
RaiseLastOSError(Registry.LastError);
That being said, you are opening the key for read-only access, but are then trying to write to the key. That is likely why WriteString()
is failing. You need to use KEY_WRITE
instead, or better just KEY_SET_VALUE
(since KEY_WRITE
includes permissions that WriteString()
doesn't need in this particular situation), eg:
var
Registry: TRegistry;
begin
Registry := TRegistry.Create(KEY_SET_VALUE{KEY_WRITE});
try
Registry.RootKey := HKEY_LOCAL_MACHINE;
if not Registry.OpenKey(KeyLocation, True) then
RaiseLastOSError(Registry.LastError);
Registry.WriteString('Value1', 'text123');
finally
Registry.Free;
end;
end;
That being said, do note that you are trying to write to HKEY_LOCAL_MACHINE
, which by default only admins have write access to. So yes, you will have to either run your code with elevated rights, or else adjust the Registry permissions to grant write access to a non-admin user and then run your code as that user.
Also, if you are running on a 64bit machine, you might need to explicitly specify whether you want to access the 32bit (KEY_WOW64_32KEY
) or 64bit (KEY_WOW64_32KEY
) section of the Registry. See Accessing An Alternate Registry View.
KeyLocation
correct, have you checked ? Does it has the correct slashes (I think it should also end with a slash in this case)