4

使用下面的代码,我尝试在注册表的 HKEY_LOCAL_MACHINE 部分设置一个值,但我收到错误“无法为.....设置数据”如果我使用 HKEY_CURRENT_USER 没有问题。

我可能在这里缺少什么。

(代码不完整,但我认为是它的重要部分)

type
  TTypWinBits = (Bit32, Bit64);

function WinBits: TTypWinBits;
type
  TIsWow64Process = function(Handle:THandle; var IsWow64 : BOOL) : BOOL; stdcall;
var
  hKernel32 : Integer;
  IsWow64Process : TIsWow64Process;
  IsWow64 : BOOL;
begin
  Result := Bit32;
  hKernel32 := LoadLibrary('kernel32.dll');
  if (hKernel32 = 0) then RaiseLastOSError;
  @IsWow64Process := GetProcAddress(hkernel32, 'IsWow64Process');
  if Assigned(IsWow64Process) then
    begin
      IsWow64 := False;
      if (IsWow64Process(GetCurrentProcess, IsWow64)) then
        Result := Bit64
      else
        RaiseLastOSError;
    end;
  FreeLibrary(hKernel32);
end;

function TFastRegistry.CreateConnection: TRegistry;
begin
  Result := TRegistry.Create;
  try
    case WinBits of
      Bit32: Result := TRegistry.Create;
      Bit64: Result := TRegistry.Create(KEY_WRITE OR KEY_WOW64_64KEY);
    end;
  except
    on E: exception do
      Result := nil;
  end;
end;

procedure TFastRegistry.RunAdd(aDesc, aName: string);
var
  Reg: TRegistry;
  sRegKey: String;
begin
  sRegKey := 'Software\Microsoft\Windows\CurrentVersion\Run';
  Reg := CreateConnection;
  with Reg do
    begin
      try
        RootKey := HKEY_LOCAL_MACHINE;
        if not KeyExists(sRegKey) then
          OpenKey(sRegKey, True)
        else
          OpenKey(sRegKey, False);
        WriteString(aDesc, aName);
      finally
        CloseKey;
        Free;
      end;
    end;
end;
4

2 回答 2

6

程序需要提升权限才能写入本地计算机密钥。如您所见,没有它,功能将失败。如果您的程序应该是一个管理工具,那么请使用清单文件,以便操作系统会提示您获得许可。如果您不需要,请改为写入当前用户密钥,这样它就不会影响系统上的所有帐户。

于 2012-07-28T13:58:53.607 回答
0

您只需要通过“免费”释放句柄,然后在寄存器中的下一个条目重新创建它,而不是永久设置并通过 OpenKey 和 CloseKey 打开和关闭它们!它看起来像一个错误:-)

于 2013-10-20T17:22:07.387 回答