Get Registry Key Path by the Key Handle (HKEY)
This code shows a way for getting the string with full path to already opened registry key by its known integer handle.
function RegGetKeyFullName(const hKey:dword;pRoot:pdword):string;
var Sz,hDll:dword;
P:PWideChar;
ZwQueryKey:function (hK, KeyInfCls, KeyInformation, Length:dword; var ResultLength:dword):dword; stdcall;
begin
Result := '';
if hKey = INVALID_HANDLE_VALUE then exit;
hDll := LoadLibrary('ntdll.dll');
if hDll <> 0 then begin
@ZwQueryKey := GetProcAddress(hDll, 'ZwQueryKey');
if @ZwQueryKey<>nil /b>then begin
ZwQueryKey(hKey, 3, 0, 0, Sz);
Sz := Sz + 2;
P := Pointer(LocalAlloc(LPTR, Sz));
ZwQueryKey(hKey, 3, Cardinal(P), Sz, Sz);
Result := String(WideString(PWChar(@(P[2]))));
LocalFree(Cardinal(P));
if pRoot <> nil then begin
if Pos('\MACHINE\', Result) = 10 then begin
pRoot^ := HKEY_LOCAL_MACHINE;
Result := Copy(Result, 19, Length(Result));
end else
if Pos('\USER\',Result) = 10 then begin
pRoot^ := HKEY_CURRENT_USER;
Result := Copy(Result, 16, Length(Result));
Result := Copy(Result, Pos('\',Result)+1, Length(Result));
end else pRoot^ := 0;
end;
end;
FreeLibrary(hDll);
end;
end;