I have a small Delphi application that writes a key to the LOCAL_MACHINE registry. When I run it on Windows 7 professional with user that has administrator privileges it fails to write the value, but when I right click and choose "Run as administrator" it does work.
The code is:
var
reg : TRegistry;
begin
Result := false;
reg := TRegistry.Create;
reg.RootKey := HKE开发者_开发知识库Y_LOCAL_MACHINE;
if (reg.OpenKey('Software\YepYep', TRUE)) then
Begin
try
reg.WriteString('ProductKey', Trim(ProductKey));
Result := true;
finally
reg.CloseKey();
end;
End;
reg.Free;
end;
The computer UAC settings are set to "Notify only when programs try to make changes to my computer" (second lowest level). When I take it down to "Never notify" it also works (with no need to use "Run as administrator").
If you have any ideas/thoughts about what could be the issue, I would appreciate hearing them.
Thanks.
Simply put, a user needs administrator rights to write to HKLM. Likewise for writing to system directories (system32, program files). This has always been true for Windows versions that implemented security (NT, 2k, XP, Vista, 7).
Under UAC, users in the administrators group run processes, by default, with a standard user token. So they do not get write access to HKLM etc.
You really need to read up on UAC before going much further. Start here.
Once you are familiar with the issues you have two principal options:
- Add a
requireAdministrator
manifest to your application so that it always runs with elevated privileges. This means that the user will have to negotiate the UAC dialog every time they start your application. - Rework your application so that it does not write to HKLM. A common approach is to do everything that needs admin rights during installation which typically happens elevated. Another variant is to hive off the small part of your app that needs admin rights to a separate process so that you only present UAC dialogs when necessary.
Of these two options, number 2 is most definitely to be preferred. Bear in mind that your application already did not work on 2000/XP for non-administrator users.
Administrator accounts have limited access because of UAC - that is the design of Windows Vista and Windows 7. HKEY_LOCAL_MACHINE
is a very protected space.
You can include a manifest to prompt when starting your application.
Starting from Vista, applications can no longer write to this part of the registry. When writing to HKEY_LOCAL_MACHINE\Software your application needs elevated privileges. To provide backwards XP compatibility they invented registry virtualization: http://msdn.microsoft.com/en-us/library/aa965884 please read the ms page and you will understand why your application does not work when not running as administrator...
精彩评论