使用Delphi

时间:2018-02-16 12:30:36

标签: delphi registry

Delphi提供了库System.Win.Registry来操作windows注册表。 不幸的是,它不包含注册表数据类型REG_MULTI_SZ的读/写过程(=字符串列表)。

以下代码返回带有“无效数据类型”的ERegistryException - 它似乎只适用于数据类型REG_SZ:

  Registry := TRegistry.Create;
  Registry.RootKey := HKEY_LOCAL_MACHINE;
  Registry.OpenKey(cKey, false);
  sValue := Registry.ReadString('MyRegEntry');

同时我可以用

读取REG_MULTI_SZ值
  Registry.ReadBinaryData('MyRegEntry', pBuf, sizeof(pBuf));

但是如果我使用WriteBinaryData()将其写回来,它将作为数据类型REG_BINARY而不是REG_MULTI_SZ写入注册表。所以这不能正常工作。

如何使用Delphi操作数据类型REG_MULTI_SZ的注册表数据?

1 个答案:

答案 0 :(得分:0)

我编写了两个函数(类助手)来扩展TRegistry的功能:

unit Common.RegistryHelper;

interface

uses
  System.Classes, System.Win.Registry, Winapi.Windows, System.Math;

type
  TRegistryHelper = class helper for TRegistry
  public
    function ReadMultiSz(const name: string; var Strings: TStrings): boolean;
    function WriteMultiSz(const name: string; const value: TStrings): boolean;
  end;

implementation

function TRegistryHelper.ReadMultiSz(const name: string; var Strings: TStrings): boolean;
var
  iSizeInByte: integer;
  Buffer: array of WChar;
  iWCharsInBuffer: integer;
  z: integer;
  sString: string;
begin
  iSizeInByte := GetDataSize(name);
  if iSizeInByte > 0 then begin
    SetLength(Buffer, Floor(iSizeInByte / sizeof(WChar)));
    iWCharsInBuffer := Floor(ReadBinaryData(name, Buffer[0],
      iSizeInByte) / sizeof(WChar));
    sString := '';
    for z := 0 to iWCharsInBuffer do begin
      if Buffer[z] <> #0 then begin
        sString := sString + Buffer[z];
      end else begin
        if sString <> '' then begin
          Strings.Append(sString);
          sString := '';
        end;
      end;
    end;
    result := true;
  end else begin
    result := false;
  end;
end;

function TRegistryHelper.WriteMultiSz(const name: string; const value: TStrings): boolean;
var
  sContent: string;
  x: integer;
begin
  sContent := '';
  for x := 0 to pred(value.Count) do begin
    sContent := sContent + value.Strings[x] + #0;
  end;
  sContent := sContent + #0;
  result := RegSetValueEx(CurrentKey, pchar(name), 0, REG_MULTI_SZ,
    pointer(sContent), Length(sContent)*sizeof(Char)) = 0;
end;

end.

使用上面的函数,您只需在程序中写入以下代码即可向REG_MULTI_SZ条目添加值:

procedure AddValueToRegistry();
const
  cKey = '\SYSTEM\ControlSet001\services\TcSysSrv';
var
  Registry: TRegistry;
  MyList: TStrings;
begin
  Registry := TRegistry.Create;
  Registry.RootKey := HKEY_LOCAL_MACHINE;
  Registry.OpenKey(cKey, false);
  try
    MyList := TStringList.Create();
    Registry.ReadMultiSz('MyRegEntry', MyList);
    MyList.Add('NewEntry');
    Registry.WriteMultiSz('MyRegEntry', MyList);
  finally
    MyList.Free;
  end;
  Registry.Free;
end;