我正在使用一个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;
但它也无效。
答案 0 :(得分:11)
你的其他部分没有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;
答案 1 :(得分:0)
您可能需要考虑使用HKEY_CURRENT_USER而不是HKEY_LOCAL_MACHINE。
在Vista / 7/8中,除非使用管理员权限运行程序,否则实际上不会获得HKEY_LOCAL_MACHINE,而是获得虚拟化位置。从本质上讲,Windows只为用户提供了一些东西。
使用HKEY_LOCAL_MACHINE只会导致后来的麻烦。 Windows一直在锁定它。