How can I read 64-bit registry key from a 32-bit process?

后端 未结 4 2013
轻奢々
轻奢々 2020-12-16 03:01

I\'ve been using the value of key MachineGuid from HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Cryptography to uniquely identify hosts, but from 32-b

4条回答
  •  再見小時候
    2020-12-16 03:27

    Your code is needlessly complex, largely because you are not taking advantage of the built-in TRegistry class which shields you from all the complexities of the low-level registry API. For example, consider the following code:

    type
      TRegistryView = (rvDefault, rvRegistry64, rvRegistry32);
    
    function RegistryViewAccessFlag(View: TRegistryView): LongWord;
    begin
      case View of
      rvDefault:
        Result := 0;
      rvRegistry64:
        Result := KEY_WOW64_64KEY;
      rvRegistry32:
        Result := KEY_WOW64_32KEY;
      end;
    end;
    
    function ReadRegStr(const Root: HKEY; const Key, Name: string;
      const View: TRegistryView=rvDefault): string;
    var
      Registry: TRegistry;
    begin
      Registry := TRegistry.Create(KEY_READ or RegistryViewAccessFlag(View));
      try
        Registry.RootKey := Root;
        if not Registry.OpenKey(Key) then
          raise ERegistryException.CreateFmt('Key not found: %s', [Key]);
        if not Registry.ValueExists(Name) then
          raise ERegistryException.CreateFmt('Name not found: %s\%s', [Key, Name]);
        Result := Registry.ReadString(Name);//will raise exception in case of failure
      finally
        Registry.Free;
      end;
    end;
    

    The function ReadRegStr will return the string value named Name from the key Key relative to the root key Root. If there is an error, for example if the key or name do not exists, or if the value is of the wrong type, then an exception will be raised.

    The View parameter is an enumeration that makes it simple for you to access native, 32-bit or 64-bit views of the registry. Note that native means native to the process that is running. So it will be the 32-bit view for a 32-bit process and the 64-bit view for a 64-bit process. This enumeration mirrors the equivalent definition in .net.

提交回复
热议问题