尝试在注册表中保存值时出错

OZ8*_*8HP 4 delphi registry 32bit-64bit

使用下面的代码我尝试在注册表的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;
Run Code Online (Sandbox Code Playgroud)

Rob*_*edy 6

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