IGroupPolicyObject.GetRegistryKey
doesn't return a .NET RegistryKey
object, it returns a Win32 registry key handle (an HKEY
). There are two useful things you can do with an IntPtr
value that contains a native HKEY. First, you can pass it to other Win32 registry access functions. If you use it this way, you also need to manually close it by calling RegCloseKey
when you're done, or it will leak the handle.
As @HansPassant helpfully points out in his comment, your second (and probably better) option is to turn it into a SafeRegistryHandle
and use it to get a RegistryKey
object:
var hkey = gpo.GetRegistryKey(GpoSectionMachine);
var safeHandle = new SafeRegistryHandle(hkey, true);
var reg = RegistryKey.FromHandle(safeHandle);
If you wrote a managed implementation of IGroupPolicyObject
and it returns an actual RegistryKey
object from this function, then:
- You did it wrong and your implementation is not portable to any other consumer of
IGroupPolicyObject
, and
- You must have manually marshalled your
RegistryKey
object into an IntPtr
in your implementation, so just do the opposite to get it back out. (But really -- don't do that, you are breaking the COM contract by returning the wrong type.)
An implementation of this method should instead be written to return a SafeRegistryHandle
(the marshaler will, I believe, automatically convert between SafeHandle
and an unmanaged handle). RegistryKey.Handle
is one of these so you can use the C# classes right up until you need to return something from your implementation.