6

我有一个 Delphi XE2 项目来使用注册表项。所以我定义了以下代码:

procedure TMainForm.BitBtn01Click(Sender: TObject);
var
  RegistryEntry: TRegistry;
begin
  RegistryEntry := TRegistry.Create(KEY_READ or KEY_WOW64_64KEY);
  RegistryEntry.RootKey:= HKEY_LOCAL_MACHINE;
  if (not RegistryEntry.KeyExists('Software\MyCompanyName\MyName\')) then
    begin
      RegistryEntry.Access:= KEY_WRITE or KEY_WOW64_64KEY;
      RegistryEntry.OpenKey('Software\MyCompanyName\MyName\',True);
      RegistryEntry.WriteString('', 'MyFirstProject');
    end
  else
    begin
      Memo01.Lines.Add(RegistryEntry.ReadString('(Default)')); //Not Working
      Memo01.Lines.Add(RegistryEntry.ReadString('')); //Not Working
      Memo01.Lines.Add(RegistryEntry.ReadString('@')); //Not Working
    end;
  RegistryEntry.CloseKey();
  RegistryEntry.Free;
end;

我的要求是检查“MyName”的默认值并显示在 Memo01 中。但什么都没有发生。所以我尝试了另一种方法如下:

procedure TMainForm.BitBtn01Click(Sender: TObject);
var
  RegistryEntry: TRegistry;
  RegistryString: string;
begin
  RegistryEntry := TRegistry.Create(KEY_READ or KEY_WOW64_64KEY);
  RegistryEntry.RootKey:= HKEY_LOCAL_MACHINE;
  if (not RegistryEntry.KeyExists('Software\MyCompanyName\MyName\')) then
    begin
      RegistryEntry.Access:= KEY_WRITE or KEY_WOW64_64KEY;
      RegistryEntry.OpenKey('Software\MyCompanyName\MyName\',True);
      RegistryEntry.WriteString('', 'MyFirstProject');
    end
  else
    begin
      RegistryString := RegistryEntry.ReadString('(Default)'); //Not Working
      RegistryString := RegistryEntry.ReadString(''); //Not Working
      RegistryString := RegistryEntry.ReadString('@'); //Not Working
      Memo01.Lines.Add(RegistryString);
    end;
  RegistryEntry.CloseKey();
  RegistryEntry.Free;
end;

但它也不起作用。

4

2 回答 2

13

您的 else 部分没有 Openkey。

Const
  C_KEY='Software\MyCompanyName\MyName\';
var
  RegistryEntry: TRegistry;
  RegistryString: string;
begin
  RegistryEntry := TRegistry.Create(KEY_READ or KEY_WOW64_64KEY);
  try
    RegistryEntry.RootKey := HKEY_LOCAL_MACHINE;
    if (not RegistryEntry.KeyExists(C_KEY)) then
    begin
      RegistryEntry.Access := KEY_WRITE or KEY_WOW64_64KEY;
      if RegistryEntry.OpenKey(C_KEY, true) then
        RegistryEntry.WriteString('', 'MyFirstProject');
    end
    else
    begin
      RegistryEntry.Access := KEY_READ or KEY_WOW64_64KEY;
      if RegistryEntry.OpenKey(C_KEY, false) then
      begin
        Memo01.Lines.Add(RegistryEntry.ReadString(''));
      end;
    end;
    RegistryEntry.CloseKey();
  finally
    RegistryEntry.Free;
  end;
end;
于 2013-04-23T18:43:14.853 回答
0

您可能要考虑使用 HKEY_CURRENT_USER 而不是 HKEY_LOCAL_MACHINE。

在 Vista/7/8 中,除非程序使用管理员权限运行,否则您实际上不会获得 HKEY_LOCAL_MACHINE,而是获得虚拟化位置。从本质上讲,Windows 为您提供了只有用户才能看到的东西。

使用 HKEY_LOCAL_MACHINE 只会在以后导致头痛。Windows 一直在锁定它。

于 2013-04-24T16:56:23.597 回答