unit uRegistoryUtils;

interface

uses
  Winapi.Windows;

function GetRegValue2(
  const iReservedKey: DWORD;
  const iAddress: String): String;

implementation

uses
  System.SysUtils;

function DeleteDelimiter(
  const iStr: String;
  const iDelimiter: String = '\'): String;
var
  Len: Cardinal;
begin
  Result := iStr;

  Len := Length(Result);
  if (Result[Len] = iDelimiter) then
    Result := Copy(Result, 1, Len - 1);
end;

procedure RegValueGetPathValue(
  const iAddress: String;
  var ioPath, ioValue: String);
begin
  ioPath := DeleteDelimiter(ExtractFilePath(iAddress));
  ioValue := ExtractFileName(iAddress);

  if (ioPath <> '') and (ioPath[1] = '\') then
    Delete(ioPath, 1, 1);
end;

function GetRegValueFull(
  const iReservedKey: DWORD;
  const iAddress, iPath, iValue: String;
  const iRegType: DWORD;
  var ioBuffSize: DWORD;
  const iBuff: Pointer): Boolean;
var
  hReg: HKEY;
  RegType: DWORD;
begin
  hReg := 0;

  RegType := iRegType;

  RegOpenKeyEx(
    iReservedKey,
    PChar(iPath),
    0,
    KEY_QUERY_VALUE,
    hReg);
  try
    Result :=
      (
        RegQueryValueEx(
          hReg,
          PChar(iValue),
          nil,
          @RegType,
          iBuff,
          @ioBuffSize
        )
        = ERROR_SUCCESS
      );
  finally
    RegCloseKey(hReg);
  end;
end;

function GetRegStringValue(
  const iReservedKey: DWORD;
  const iAddress, iPath, iValue: String): String;
var
  VarSize: DWORD;
begin
  SetLength(Result, $ff);
  VarSize := Length(Result);

  if
    (
      GetRegValueFull(
        iReservedKey,
        iAddress,
        iPath,
        iValue,
        REG_SZ,
        VarSize,
        PChar(Result)
      )
    )
  then
    Result := StrPas(PChar(Result))
  else
    Result := '';
end;

function GetRegValue2(
  const iReservedKey: DWORD;
  const iAddress: String): String;
var
  Path, Value: String;
begin
  RegValueGetPathValue(iAddress, Path, Value);

  Result :=
    GetRegStringValue(iReservedKey, iAddress, Path, Value);
end;

end.
