Desktop Functions: Smart Device Functions:
|
Search Results for "registry" in [All]odbc32On XP, Win2k and Win2k3, the system DSN's are stored in the registry in
Dim key As Microsoft.Win32.RegistryKey
key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("software\odbc\odbc.ini\odbc data sources") wininet2: InternetOpen const int INTERNET_OPEN_TYPE_PRECONFIG = 0; // use registry configuration Const INTERNET_OPEN_TYPE_PRECONFIG = 0 ' // use registry configuration user32
CDS_UPDATEREGISTRY = 0x00000001,
CDS_UPDATEREGISTRY = &H1
ChangeDisplaySettingsEx(d.DeviceName, ref dm, IntPtr.Zero, CDS_UPDATEREGISTRY, IntPtr.Zero);
CDS_UPDATEREGISTRY = 0x00000001,
CDS_UPDATEREGISTRY = &H1
RegistryKey root;
RegistryKey rk;
root = Registry.LocalMachine;
root = Registry.ClassesRoot;
RegistryKey root;
RegistryKey rk;
root = Registry.LocalMachine;
root = Registry.ClassesRoot; 7: SetSysColors This function changes the color for the current session only. To persist the change, you must update the registry keys at HKEY_CURRENT_USER\Control Panel\Colors
//save value in registry so that it will persist
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Control Panel\\Colors", true); shell32lpVerb member can be used for a varity of actions like "properties", "find", "openas", "print"..etc depending on the file type you're dealing with.Actions available for a specific file type are stored in registry, setting lpVerb to null results in the default action of that file type to be executed. setupapi
public static extern int CM_Get_DevNode_Registry_Property(
out Microsoft.Win32.RegistryValueKind pulRegDataType,
Declare Function CM_Get_DevNode_Registry_Property Lib "setupapi.dll" (TODO) As TODO property, A CM_DRP_-prefixed constant value that identifies the device property to be obtained from the registry. These constants are defined in Cfgmgr32.h. pulRegDataType, Optional, can be NULL. A pointer to a location that receives the registry data type, specified as a REG_-prefixed constant defined in Winnt.h. In most cases you can use SetupDiGetDeviceRegistryProperty. Also Microsoft.Win32.RegistryValueKind only contains enumerations for the basic kinds.
Microsoft.Win32.RegistryValueKind kind;
CM_Get_DevNode_Registry_Property(devinst, CM_DRP_DRIVER, out kind, IntPtr.Zero, ref length, 0);
if (CR_SUCCESS == CM_Get_DevNode_Registry_Property(devinst, CM_DRP_DRIVER, out kind, buffer, ref length, 0))
SetupDiGetDeviceRegistryProperty(NewDeviceInfoSet, DeviceInfoData, DirectCast(SPDRP_FRIENDLYNAME, Integer), propRegDataType, sbDesc, MAX_LEN, reqSize)
SetupDiGetDeviceRegistryProperty(NewDeviceInfoSet, DeviceInfoData, DirectCast(SPDRP_DEVICEDESC, Integer), propRegDataType, sbDesc, MAX_LEN, reqSize)
SetupDiGetDeviceRegistryProperty(NewDeviceInfoSet, DeviceInfoData, DirectCast(SPDRP_HARDWAREID, Integer), propRegDataType, sbHWID, MAX_LEN, reqSize) DIBCI_NOINSTALLCLASS // Exclude a class if it has the NoInstallClass value entry in its registry key. DIBCI_NODISPLAYCLASS // Exclude a class if it has the NoDisplayClass value entry in its registry key.
if (SetupDiGetDeviceRegistryProperty(h, ref da, SPDRP_DRIVER, ref RegType, ptrBuf, BUFFER_SIZE, ref RequiredSize))
if (SetupDiGetDeviceRegistryProperty(h, ref da, SPDRP_DEVICEDESC, ref RegType, ptrBuf, BUFFER_SIZE, ref RequiredSize))
if (SetupDiGetDeviceRegistryProperty(h, ref da, SPDRP_DRIVER, ref RegType, ptrBuf, BUFFER_SIZE, ref RequiredSize))
'goes through all devices matching the HID guid and finds one with a registry entry string matching the name of the desired HID device, in this case a Midi device
Dim devEnumInterfaceResult, devDetailResult, devEnumResult, destructionResult, registryPropertyResult As Boolean
registryPropertyResult = SetupDiGetDeviceRegistryProperty(h, da, DeviceRegistryValueNames.SPDRP_DEVICEDESC, RegType, ptrButter, 0, RequiredSize)
registryPropertyResult = SetupDiGetDeviceRegistryProperty(h, da, DeviceRegistryValueNames.SPDRP_DEVICEDESC, RegType, ptrButter, RequiredSize, RequiredSize)
If registryPropertyResult Then
registryPropertyResult = SetupDiGetDeviceRegistryProperty(h, da, DeviceRegistryValueNames.SPDRP_DRIVER, RegType, ptrButter, RequiredSize, RequiredSize)
registryPropertyResult = SetupDiGetDeviceRegistryProperty(h, da, DeviceRegistryValueNames.SPDRP_DRIVER, RegType, ptrButter, RequiredSize, RequiredSize)
If registryPropertyResult Then
public static extern bool SetupDiGetDeviceRegistryProperty(
public static extern bool SetupDiGetDeviceRegistryProperty( propertyRegDataType, Pointer to a variable that receives the registry data Type. This parameter can be NULL.</param>
Public Shared Function SetupDiGetDeviceRegistryProperty( _
/// Flags for SetupDiGetDeviceRegistryProperty().
enum SetupDiGetDeviceRegistryPropertyEnum : uint
if (SetupDiGetDeviceRegistryProperty(h, ref da, SPDRP_DEVICEDESC, out RegType, ptrBuf, BUFFER_SIZE, out RequiredSize))
if (SetupDiGetDeviceRegistryProperty(h, ref da, SPDRP_DRIVER, out RegType, ptrBuf, BUFFER_SIZE, out RequiredSize))
if ( SetupDiGetDeviceRegistryProperty(h, ref da, SPDRP_DEVICEDESC, out regType, ptrBuffer, BUFFER_SIZE, out RequiredSize) )
if ( SetupDiGetDeviceRegistryProperty(h, ref da, SPDRP_DRIVER, out regType, ptrBuffer, BUFFER_SIZE, out RequiredSize) ) urlmon
private const int SET_FEATURE_IN_REGISTRY = 0x00000004; ntdll
SystemRegistryQuotaInformation = 0x0025,
SystemRegistryAppendString = 0x006E, advapi3219: DefaultPassword
For Registry Keys
System.Security.AccessControl.RegistrySecurity 21: GetSecurityInfo
Registry keys
SE_REGISTRY_KEY,
SE_REGISTRY_WOW64_32KEY But LsaStorePrivatData is still usefull for storing DefaultPassword in LSA and avoid to have the password in cleartext in registry. 23: RegCloseKey Microsoft.Win32.RegistryKey.Close() Method. (Special Note: The .NET Framework (3.0 and earlier at least) cannot read registry values of special types (for example: REG_RESOURCE_LIST and REG_FULL_RESOURCE_DESCRIPTOR). I am not sure if they will ever be available under .NET, to see examples of these types of values at work, visit your registry under (HKLM\HARDWARE\DESCRIPTION\System) and (HKLM\HARDWARE\RESOURCEMAP\Hardware Abstraction Layer\ACPI x86 platform).
static extern int RegConnectRegistry(string lpmachineName, int hKey, ref int phKResult);
Declare Auto Function RegConnectRegistry Lib "Advapi32" ( _ Windows.Win32.RegistryKey.OpenRemoteBaseKey
LONG RegConnectRegistry(
Public Shared Function OpenRemoteBaseKey(ByVal Hive As RegistryHive, ByVal RemotePC As String) As RegistryKey
ret = RegConnectRegistry("\\" & RemotePC, New IntPtr(Hive), hRemoteKey)
Dim ans As New RegistryKey
public RemoteRegistryReader(string computerName)
iReturn = RegConnectRegistry(computerName, HKEY, ref iResult); 25: RegCopyTree
26: RegCreateKeyA [Microsoft.Win32.RegistryKey.CreateSubKey] 27: RegCreateKeyEx
NOT EXECUTABLE!!! PLEASE USE "Microsoft.Win32.Registry" and "Microsoft.Win32.RegistryKey" Microsoft.Win32.RegistryKey.CreateSubKey 28: RegDeleteKey Microsoft.Win32.RegistryKey.DeleteSubKey() (the non-WOW64 version)
29: RegDeleteKeyEx Microsoft.Win32.RegistryKey.DeleteSubKey() (the non-WOW64 version)
30: RegDeleteTree
hiveKey = Registry.LocalMachine.OpenSubKey(subKey); Type type = typeof(RegistryKey); 32: RegEnumKeyEx Microsoft.Win32.RegistryKey.GetSubKeyNames()
Throw New ApplicationException("Cannot access a closed registry key") 33: RegEnumValue
35: RegGetValue
/* Retrieves the type and data for the specified registry value. */
SafeRegistryHandle hkey,
/* Retrieves the type and data for the specified registry value. */ Microsoft.Win32.Registry.GetValue()
static extern TODO RegistryChangeMonitor(TODO);
Declare Function RegistryChangeMonitor Lib "advapi32.dll" (TODO) As TODO 37: RegLoadKey When run from a remote PC (via RegConnectRegistry), the path to the hive file is local to that PC.
Public Shared Sub LoadKey(ByVal key As RegistryKey, ByVal MountPoint As String, ByVal HivePath As String) RegSaveKey to save registry key to file RegRestoreKey to restore registry key from a file // RegistryChangeMonitor.cs
public delegate void RegistryChangeHandler(object sender, RegistryChangeEventArgs e);
public class RegistryChangeMonitor : IDisposable
private string _registryPath;
private RegistryKey _monitorKey;
public RegistryChangeMonitor(string registryPath) : this(registryPath, REG_NOTIFY_CHANGE.LAST_SET) { ; }
public RegistryChangeMonitor(string registryPath, REG_NOTIFY_CHANGE filter)
this._registryPath = registryPath.ToUpper();
~RegistryChangeMonitor()
if (this._registryPath.StartsWith("HKEY_CLASSES_ROOT"))
this._monitorKey = Registry.ClassesRoot.OpenSubKey(this._registryPath.Substring(18));
else if (this._registryPath.StartsWith("HKCR"))
this._monitorKey = Registry.ClassesRoot.OpenSubKey(this._registryPath.Substring(5));
else if (this._registryPath.StartsWith("HKEY_CURRENT_USER"))
this._monitorKey = Registry.CurrentUser.OpenSubKey(this._registryPath.Substring(18));
else if (this._registryPath.StartsWith("HKCU"))
this._monitorKey = Registry.CurrentUser.OpenSubKey(this._registryPath.Substring(5));
else if (this._registryPath.StartsWith("HKEY_LOCAL_MACHINE"))
this._monitorKey = Registry.LocalMachine.OpenSubKey(this._registryPath.Substring(19));
else if (this._registryPath.StartsWith("HKLM"))
this._monitorKey = Registry.LocalMachine.OpenSubKey(this._registryPath.Substring(5));
else if (this._registryPath.StartsWith("HKEY_USERS"))
this._monitorKey = Registry.Users.OpenSubKey(this._registryPath.Substring(11));
else if (this._registryPath.StartsWith("HKU"))
this._monitorKey = Registry.Users.OpenSubKey(this._registryPath.Substring(4));
else if (this._registryPath.StartsWith("HKEY_CURRENT_CONFIG"))
this._monitorKey = Registry.CurrentConfig.OpenSubKey(this._registryPath.Substring(20));
else if (this._registryPath.StartsWith("HKCC"))
this._monitorKey = Registry.CurrentConfig.OpenSubKey(this._registryPath.Substring(5));
object hkey = typeof(RegistryKey).InvokeMember(
RegistryChangeEventArgs e = new RegistryChangeEventArgs(this);
RegistryChangeEventArgs e = new RegistryChangeEventArgs(this);
RegistryChangeEventArgs e = new RegistryChangeEventArgs(this);
public event RegistryChangeHandler Changed;
public event RegistryChangeHandler Error; // RegistryChangeEventArgs.cs
public class RegistryChangeEventArgs : EventArgs
private RegistryChangeMonitor _monitor;
public RegistryChangeEventArgs(RegistryChangeMonitor monitor)
public RegistryChangeMonitor Monitor 39: RegOpenKey The current managed versions of OpenSubKey do not support read/writing from the different registry "views" on 64-bit operating systems. So, you're forced to the the APIs to accomplish this feat. See the example below for a "drop in" replacement for OpenSubKey Note that the root key should specify the registry path above where WOW6432node gets inserted, otherwise the KEY_WOW64_64 flag is ignored when used in a 32 bit application running on a 64 bit machine. So
ReadRegKey(_getRegistryKeyHandle(Registry.LocalMachine.CreateSubKey( @"Software\SomeCompany")),"OurProduct", "InstalledVersion");
Public Enum RegistryRights As Integer
Public Function OpenSubKey(ByVal Name As String) As RegistryKey
Public Function OpenSubKey(ByVal Name As String, ByVal Writeable As Boolean) As RegistryKey
Public Function OpenSubKey(ByVal Name As String, ByVal Writeable As Boolean, ByVal Options As RegWow64Options) As RegistryKey
Throw New ApplicationException("Cannot access a closed registry key")
Rights = RegistryRights.ReadKey
Rights = RegistryRights.WriteKey
Dim ans As New RegistryKey Sample Code (VB) to convert an IntPtr to a RegistryKey
Public Shared Function PointerToRegistryKey(ByVal hKey As IntPtr, ByVal writable As Boolean, ByVal ownsHandle As Boolean) As RegistryKey
' Create a SafeHandles.SafeRegistryHandle from this pointer - this is a private class
Dim safeRegistryHandleType = GetType(SafeHandles.SafeHandleZeroOrMinusOneIsInvalid).Assembly.GetType("Microsoft.Win32.SafeHandles.SafeRegistryHandle")
Dim safeRegistryHandleConstructorTypes As System.Type() = {GetType(IntPtr), GetType(Boolean)}
Dim safeRegistryHandleConstructor = safeRegistryHandleType.GetConstructor(privateConstructors, Nothing, safeRegistryHandleConstructorTypes, Nothing)
Dim safeHandle = safeRegistryHandleConstructor.Invoke(New Object() {hKey, ownsHandle})
' Create a new Registry key using the private constructor using the safeHandle - this should then behave like a .NET natively opened handle and disposed of correctly
Dim registryKeyType = GetType(RegistryKey)
Dim registryKeyConstructorTypes As System.Type() = {safeRegistryHandleType, GetType(Boolean)}
Dim registryKeyConstructor = registryKeyType.GetConstructor(privateConstructors, Nothing, registryKeyConstructorTypes, Nothing)
Dim result = DirectCast(registryKeyConstructor.Invoke(New Object() {safeHandle, writable}), RegistryKey) Microsoft.Win32.Registry.BaseKeyName.OpenSubKey("[KeyName]")
' Basis from http://blogs.msdn.com/cumgranosalis/archive/2005/12/09/Win64RegistryPart1.aspx
Private Function GetRegistryKeyHandle(ByVal RegisteryKey As Microsoft.Win32.RegistryKey) As System.IntPtr
Dim Type As System.Type = System.Type.GetType("Microsoft.Win32.RegistryKey")
Private Enum RegistryRights As System.Int32
Public Function OpenSubKey(ByVal ParentKey As Microsoft.Win32.RegistryKey, ByVal SubKeyName As String, ByVal Writeable As Boolean, ByVal Options As RegWow64Options) As Microsoft.Win32.RegistryKey
If ParentKey Is Nothing OrElse GetRegistryKeyHandle(ParentKey).Equals(System.IntPtr.Zero) Then
Dim Rights As System.Int32 = RegistryRights.ReadKey
Rights = RegistryRights.WriteKey
Dim Result As System.Int32 = RegOpenKeyEx(GetRegistryKeyHandle(ParentKey), SubKeyName, 0, Rights Or Options, SubKeyHandle)
Return PointerToRegistryKey(CType(SubKeyHandle, System.IntPtr), Writeable, False)
Private Function PointerToRegistryKey(ByVal hKey As System.IntPtr, ByVal writable As Boolean, ByVal ownsHandle As Boolean) As Microsoft.Win32.RegistryKey
' Create a SafeHandles.SafeRegistryHandle from this pointer - this is a private class
Dim safeRegistryHandleType As System.Type = GetType(Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid).Assembly.GetType("Microsoft.Win32.SafeHandles.SafeRegistryHandle")
Dim safeRegistryHandleConstructorTypes As System.Type() = {GetType(System.IntPtr), GetType(System.Boolean)}
Dim safeRegistryHandleConstructor As System.Reflection.ConstructorInfo = safeRegistryHandleType.GetConstructor(privateConstructors, Nothing, safeRegistryHandleConstructorTypes, Nothing)
Dim safeHandle As System.Object = safeRegistryHandleConstructor.Invoke(New System.Object() {hKey, ownsHandle})
' Create a new Registry key using the private constructor using the safeHandle - this should then behave like a .NET natively opened handle and disposed of correctly
Dim registryKeyType As System.Type = GetType(Microsoft.Win32.RegistryKey)
Dim registryKeyConstructorTypes As System.Type() = {safeRegistryHandleType, GetType(System.Boolean)}
Dim registryKeyConstructor As System.Reflection.ConstructorInfo = registryKeyType.GetConstructor(privateConstructors, Nothing, registryKeyConstructorTypes, Nothing)
Dim result As Microsoft.Win32.RegistryKey = DirectCast(registryKeyConstructor.Invoke(New Object() {safeHandle, writable}), Microsoft.Win32.RegistryKey)
Dim Config As Microsoft.Win32.RegistryKey = Nothing
Config = OpenSubKey(Microsoft.Win32.Registry.LocalMachine, "SOFTWARE\" & BaseName, False, RegWow64Options.KEY_WOW64_64KEY)
Config = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\" & BaseName, False)
enum RegistryRights
/// Open a registry key using the Wow64 node instead of the default 32-bit node.
RegistryKey _openSubKey(RegistryKey parentKey, string subKeyName, bool writable, RegWow64Options options)
if (parentKey == null || _getRegistryKeyHandle(parentKey) == IntPtr.Zero)
int rights = (int)RegistryRights.ReadKey;
rights = (int)RegistryRights.WriteKey;
int subKeyHandle, result = RegOpenKeyEx(_getRegistryKeyHandle(parentKey), subKeyName, 0, rights | (int)options, out subKeyHandle);
throw new Exception("Exception encountered opening registry key.", new System.ComponentModel.Win32Exception(result));
RegistryKey subKey = _pointerToRegistryKey((IntPtr)subKeyHandle, writable, true);
/// Get a pointer to a registry key.
/// <param name="registryKey">Registry key to obtain the pointer of.</param>
/// <returns>Pointer to the given registry key.</returns>
IntPtr _getRegistryKeyHandle(RegistryKey registryKey)
//Get the type of the RegistryKey
Type registryKeyType = typeof(RegistryKey);
//Get the FieldInfo of the 'hkey' member of RegistryKey
registryKeyType.GetField("hkey", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
SafeHandle handle = (SafeHandle)fieldInfo.GetValue(registryKey);
/// Get a registry key from a pointer.
/// <param name="hKey">Pointer to the registry key</param>
/// <returns>Registry key pointed to by the given pointer.</returns>
RegistryKey _pointerToRegistryKey(IntPtr hKey, bool writable, bool ownsHandle)
//Get the Type for the SafeRegistryHandle
Type safeRegistryHandleType =
typeof(Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid).Assembly.GetType("Microsoft.Win32.SafeHandles.SafeRegistryHandle");
Type[] safeRegistryHandleCtorTypes = new Type[] { typeof(IntPtr), typeof(bool) };
System.Reflection.ConstructorInfo safeRegistryHandleCtorInfo = safeRegistryHandleType.GetConstructor(
privateConstructors, null, safeRegistryHandleCtorTypes, null);
//Invoke the constructor, getting us a SafeRegistryHandle
Object safeHandle = safeRegistryHandleCtorInfo.Invoke(new Object[] { hKey, ownsHandle });
//Get the type of a RegistryKey
Type registryKeyType = typeof(RegistryKey);
Type[] registryKeyConstructorTypes = new Type[] { safeRegistryHandleType, typeof(bool) };
System.Reflection.ConstructorInfo registryKeyCtorInfo = registryKeyType.GetConstructor(
privateConstructors, null, registryKeyConstructorTypes, null);
//Invoke the constructor, getting us a RegistryKey
RegistryKey resultKey = (RegistryKey)registryKeyCtorInfo.Invoke(new Object[] { safeHandle, writable });
RegistryKey currentVersion =
Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("Microsoft").OpenSubKey("Windows NT").OpenSubKey("CurrentVersion");
RegistryKey software = _openSubKey(Registry.LocalMachine, "SOFTWARE", false, RegWow64Options.KEY_WOW64_64KEY);
RegistryKey microsoft = _openSubKey(software, "Microsoft", false, RegWow64Options.KEY_WOW64_64KEY);
RegistryKey windowsNT = _openSubKey(microsoft, "Windows NT", false, RegWow64Options.KEY_WOW64_64KEY); When I tested this API code in a tight loop, to get a value, and using the traditional RegistryKey.Close() on the returned subkey, I found that it leaked RegistryHandles. To correct this, I changed the call to pointerToRegistryKey in openSubKey to pass true (ownsHandle).
RegistryKey subKey = _pointerToRegistryKey((IntPtr)subKeyHandle, writable, true); // <-- last arg had been false All code above is for versions of .NET Framework prior to 4.0. In version 4.0, Microsoft.Win32.SafeHandles.SafeRegistryHandle is now public instead of private causing the examples above to error. This was to added support for Microsoft.Win32.RegistryView which negates the need to directly call advapi32.dll and the RegOpenKeyEx function by making the process managed. Here are examples of how to access 32-bit registry keys from a 64-bit application using .NET Framework 4.0:
Dim regkey As Microsoft.Win32.RegistryKey = Microsoft.Win32.RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, Microsoft.Win32.RegistryView.Registry32).OpenSubKey("SOFTWARE")
Microsoft.Win32.RegistryKey regkey = Microsoft.Win32.RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, Microsoft.Win32.RegistryView.Registry32).OpenSubKey("SOFTWARE") In both cases, examples would take you to HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node on 64-bit operating systems due to using RegistryView.Registry32. You 'll only have to change the '_pointerToRegistryKey' function.
/// Get a registry key from a pointer.
/// <param name="hKey">Pointer to the registry key</param>
/// <returns>Registry key pointed to by the given pointer.</returns>
RegistryKey _pointerToRegistryKey(IntPtr hKey, bool writable, bool ownsHandle)
//Get the Type for the SafeRegistryHandle
Type safeRegistryHandleType =
typeof(Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid).Assembly.GetType("Microsoft.Win32.SafeHandles.SafeRegistryHandle");
Type[] safeRegistryHandleCtorTypes = new Type[] { typeof(IntPtr), typeof(bool) };
System.Reflection.ConstructorInfo safeRegistryHandleCtorInfo = safeRegistryHandleType.GetConstructor(
publicConstructors, null, safeRegistryHandleCtorTypes, null);
//Get the SafeRegistryHandle
Microsoft.Win32.SafeHandles.SafeRegistryHandle safeHandle = (Microsoft.Win32.SafeHandles.SafeRegistryHandle)safeRegistryHandleCtorInfo.Invoke(new Object[] { hKey, ownsHandle });
//Get the RegistryKey
Microsoft.Win32.RegistryKey resultKey = Microsoft.Win32.RegistryKey.FromHandle(safeHandle); // ONLY possible under .NET 4.0! In .NET 3.5 there is no .FromHandle Method available! 40: RegOpenKeyEx The current managed versions of OpenSubKey do not support read/writing from the different registry "views" on 64-bit operating systems. So, you're forced to the the APIs to accomplish this feat. See the example below for a "drop in" replacement for OpenSubKey Note that the root key should specify the registry path above where WOW6432node gets inserted, otherwise the KEY_WOW64_64 flag is ignored when used in a 32 bit application running on a 64 bit machine. So
ReadRegKey(_getRegistryKeyHandle(Registry.LocalMachine.CreateSubKey( @"Software\SomeCompany")),"OurProduct", "InstalledVersion");
Public Enum RegistryRights As Integer
Public Function OpenSubKey(ByVal Name As String) As RegistryKey
Public Function OpenSubKey(ByVal Name As String, ByVal Writeable As Boolean) As RegistryKey
Public Function OpenSubKey(ByVal Name As String, ByVal Writeable As Boolean, ByVal Options As RegWow64Options) As RegistryKey
Throw New ApplicationException("Cannot access a closed registry key")
Rights = RegistryRights.ReadKey
Rights = RegistryRights.WriteKey
Dim ans As New RegistryKey Sample Code (VB) to convert an IntPtr to a RegistryKey
Public Shared Function PointerToRegistryKey(ByVal hKey As IntPtr, ByVal writable As Boolean, ByVal ownsHandle As Boolean) As RegistryKey
' Create a SafeHandles.SafeRegistryHandle from this pointer - this is a private class
Dim safeRegistryHandleType = GetType(SafeHandles.SafeHandleZeroOrMinusOneIsInvalid).Assembly.GetType("Microsoft.Win32.SafeHandles.SafeRegistryHandle")
Dim safeRegistryHandleConstructorTypes As System.Type() = {GetType(IntPtr), GetType(Boolean)}
Dim safeRegistryHandleConstructor = safeRegistryHandleType.GetConstructor(privateConstructors, Nothing, safeRegistryHandleConstructorTypes, Nothing)
Dim safeHandle = safeRegistryHandleConstructor.Invoke(New Object() {hKey, ownsHandle})
' Create a new Registry key using the private constructor using the safeHandle - this should then behave like a .NET natively opened handle and disposed of correctly
Dim registryKeyType = GetType(RegistryKey)
Dim registryKeyConstructorTypes As System.Type() = {safeRegistryHandleType, GetType(Boolean)}
Dim registryKeyConstructor = registryKeyType.GetConstructor(privateConstructors, Nothing, registryKeyConstructorTypes, Nothing)
Dim result = DirectCast(registryKeyConstructor.Invoke(New Object() {safeHandle, writable}), RegistryKey) Microsoft.Win32.Registry.BaseKeyName.OpenSubKey("[KeyName]")
' Basis from http://blogs.msdn.com/cumgranosalis/archive/2005/12/09/Win64RegistryPart1.aspx
Private Function GetRegistryKeyHandle(ByVal RegisteryKey As Microsoft.Win32.RegistryKey) As System.IntPtr
Dim Type As System.Type = System.Type.GetType("Microsoft.Win32.RegistryKey")
Private Enum RegistryRights As System.Int32
Public Function OpenSubKey(ByVal ParentKey As Microsoft.Win32.RegistryKey, ByVal SubKeyName As String, ByVal Writeable As Boolean, ByVal Options As RegWow64Options) As Microsoft.Win32.RegistryKey
If ParentKey Is Nothing OrElse GetRegistryKeyHandle(ParentKey).Equals(System.IntPtr.Zero) Then
Dim Rights As System.Int32 = RegistryRights.ReadKey
Rights = RegistryRights.WriteKey
Dim Result As System.Int32 = RegOpenKeyEx(GetRegistryKeyHandle(ParentKey), SubKeyName, 0, Rights Or Options, SubKeyHandle)
Return PointerToRegistryKey(CType(SubKeyHandle, System.IntPtr), Writeable, False)
Private Function PointerToRegistryKey(ByVal hKey As System.IntPtr, ByVal writable As Boolean, ByVal ownsHandle As Boolean) As Microsoft.Win32.RegistryKey
' Create a SafeHandles.SafeRegistryHandle from this pointer - this is a private class
Dim safeRegistryHandleType As System.Type = GetType(Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid).Assembly.GetType("Microsoft.Win32.SafeHandles.SafeRegistryHandle")
Dim safeRegistryHandleConstructorTypes As System.Type() = {GetType(System.IntPtr), GetType(System.Boolean)}
Dim safeRegistryHandleConstructor As System.Reflection.ConstructorInfo = safeRegistryHandleType.GetConstructor(privateConstructors, Nothing, safeRegistryHandleConstructorTypes, Nothing)
Dim safeHandle As System.Object = safeRegistryHandleConstructor.Invoke(New System.Object() {hKey, ownsHandle})
' Create a new Registry key using the private constructor using the safeHandle - this should then behave like a .NET natively opened handle and disposed of correctly
Dim registryKeyType As System.Type = GetType(Microsoft.Win32.RegistryKey)
Dim registryKeyConstructorTypes As System.Type() = {safeRegistryHandleType, GetType(System.Boolean)}
Dim registryKeyConstructor As System.Reflection.ConstructorInfo = registryKeyType.GetConstructor(privateConstructors, Nothing, registryKeyConstructorTypes, Nothing)
Dim result As Microsoft.Win32.RegistryKey = DirectCast(registryKeyConstructor.Invoke(New Object() {safeHandle, writable}), Microsoft.Win32.RegistryKey)
Dim Config As Microsoft.Win32.RegistryKey = Nothing
Config = OpenSubKey(Microsoft.Win32.Registry.LocalMachine, "SOFTWARE\" & BaseName, False, RegWow64Options.KEY_WOW64_64KEY)
Config = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\" & BaseName, False)
enum RegistryRights
/// Open a registry key using the Wow64 node instead of the default 32-bit node.
RegistryKey _openSubKey(RegistryKey parentKey, string subKeyName, bool writable, RegWow64Options options)
if (parentKey == null || _getRegistryKeyHandle(parentKey) == IntPtr.Zero)
int rights = (int)RegistryRights.ReadKey;
rights = (int)RegistryRights.WriteKey;
int subKeyHandle, result = RegOpenKeyEx(_getRegistryKeyHandle(parentKey), subKeyName, 0, rights | (int)options, out subKeyHandle);
throw new Exception("Exception encountered opening registry key.", new System.ComponentModel.Win32Exception(result));
RegistryKey subKey = _pointerToRegistryKey((IntPtr)subKeyHandle, writable, false);
/// Get a pointer to a registry key.
/// <param name="registryKey">Registry key to obtain the pointer of.</param>
/// <returns>Pointer to the given registry key.</returns>
IntPtr _getRegistryKeyHandle(RegistryKey registryKey)
//Get the type of the RegistryKey
Type registryKeyType = typeof(RegistryKey);
//Get the FieldInfo of the 'hkey' member of RegistryKey
registryKeyType.GetField("hkey", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
SafeHandle handle = (SafeHandle)fieldInfo.GetValue(registryKey);
/// Get a registry key from a pointer.
/// <param name="hKey">Pointer to the registry key</param>
/// <returns>Registry key pointed to by the given pointer.</returns>
RegistryKey _pointerToRegistryKey(IntPtr hKey, bool writable, bool ownsHandle)
//Get the Type for the SafeRegistryHandle
Type safeRegistryHandleType =
typeof(Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid).Assembly.GetType("Microsoft.Win32.SafeHandles.SafeRegistryHandle");
Type[] safeRegistryHandleCtorTypes = new Type[] { typeof(IntPtr), typeof(bool) };
System.Reflection.ConstructorInfo safeRegistryHandleCtorInfo = safeRegistryHandleType.GetConstructor(
privateConstructors, null, safeRegistryHandleCtorTypes, null);
//Invoke the constructor, getting us a SafeRegistryHandle
Object safeHandle = safeRegistryHandleCtorInfo.Invoke(new Object[] { hKey, ownsHandle });
//Get the type of a RegistryKey
Type registryKeyType = typeof(RegistryKey);
Type[] registryKeyConstructorTypes = new Type[] { safeRegistryHandleType, typeof(bool) };
System.Reflection.ConstructorInfo registryKeyCtorInfo = registryKeyType.GetConstructor(
privateConstructors, null, registryKeyConstructorTypes, null);
//Invoke the constructor, getting us a RegistryKey
RegistryKey resultKey = (RegistryKey)registryKeyCtorInfo.Invoke(new Object[] { safeHandle, writable });
RegistryKey currentVersion =
Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("Microsoft").OpenSubKey("Windows NT").OpenSubKey("CurrentVersion");
RegistryKey software = _openSubKey(Registry.LocalMachine, "SOFTWARE", false, RegWow64Options.KEY_WOW64_64KEY);
RegistryKey microsoft = _openSubKey(software, "Microsoft", false, RegWow64Options.KEY_WOW64_64KEY);
RegistryKey windowsNT = _openSubKey(microsoft, "Windows NT", false, RegWow64Options.KEY_WOW64_64KEY); All code above is for versions of .NET Framework prior to 4.0. In version 4.0, Microsoft.Win32.SafeHandles.SafeRegistryHandle is now public instead of private causing the examples above to error. This was to added support for Microsoft.Win32.RegistryView which negates the need to directly call advapi32.dll and the RegOpenKeyEx function by making the process managed. Here are examples of how to access 32-bit registry keys from a 64-bit application using .NET Framework 4.0:
Dim regkey As Microsoft.Win32.RegistryKey = Microsoft.Win32.RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, Microsoft.Win32.RegistryView.Registry32).OpenSubKey("SOFTWARE")
Microsoft.Win32.RegistryKey regkey = Microsoft.Win32.RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, Microsoft.Win32.RegistryView.Registry32).OpenSubKey("SOFTWARE") In both cases, examples would take you to HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node on 64-bit operating systems due to using RegistryView.Registry32. You 'll only have to change the '_pointerToRegistryKey' function.
/// Get a registry key from a pointer.
/// <param name="hKey">Pointer to the registry key</param>
/// <returns>Registry key pointed to by the given pointer.</returns>
RegistryKey _pointerToRegistryKey(IntPtr hKey, bool writable, bool ownsHandle)
//Get the Type for the SafeRegistryHandle
Type safeRegistryHandleType =
typeof(Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid).Assembly.GetType("Microsoft.Win32.SafeHandles.SafeRegistryHandle");
Type[] safeRegistryHandleCtorTypes = new Type[] { typeof(IntPtr), typeof(bool) };
System.Reflection.ConstructorInfo safeRegistryHandleCtorInfo = safeRegistryHandleType.GetConstructor(
publicConstructors, null, safeRegistryHandleCtorTypes, null);
//Get the SafeRegistryHandle
Microsoft.Win32.SafeHandles.SafeRegistryHandle safeHandle = (Microsoft.Win32.SafeHandles.SafeRegistryHandle)safeRegistryHandleCtorInfo.Invoke(new Object[] { hKey, ownsHandle });
//Get the RegistryKey
Microsoft.Win32.RegistryKey resultKey = Microsoft.Win32.RegistryKey.FromHandle(safeHandle); // ONLY possible under .NET 4.0! In .NET 3.5 there is no .FromHandle Method available! 41: RegQueryValue
ref RegistryValueKind lpType, Managed APIs won't let you get raw REG_EXPAND_SZ values. You'll be forced to use Win32 APIs for this. Also, since .NET won't give access to the key pointer (hKey), you'll have to browse the registry using pInvoke or use Reflection to query the private member (see sample code for how to).
Dim environmentReg As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SYSTEM\CurrentControlSet\Control\Session Manager\Environment", True)
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, registryPath, 0, READ_FLAG_MASK, out hKey) == 0)
RegistryValueKind type = RegistryValueKind.Unknown;
Logger.WriteLog("Error querying value '{0}\\{1}: 0x{2:x}, return code: {3}", registryPath, valName, Marshal.GetLastWin32Error(), retVal);
case RegistryValueKind.String:
case RegistryValueKind.DWord:
case RegistryValueKind.QWord:
Logger.WriteLog("Error opening registry key HKLM\\{0}: {1:x}", registryPath, Marshal.GetLastWin32Error()); classes Registery, RegistryKey 42: RegQueryValueEx
ref RegistryValueKind lpType, Managed APIs won't let you get raw REG_EXPAND_SZ values. You'll be forced to use Win32 APIs for this. Also, since .NET won't give access to the key pointer (hKey), you'll have to browse the registry using pInvoke or use Reflection to query the private member (see sample code for how to).
Dim environmentReg As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SYSTEM\CurrentControlSet\Control\Session Manager\Environment", True)
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, registryPath, 0, READ_FLAG_MASK, out hKey) == 0)
RegistryValueKind type = RegistryValueKind.Unknown;
Logger.WriteLog("Error querying value '{0}\\{1}: 0x{2:x}, return code: {3}", registryPath, valName, Marshal.GetLastWin32Error(), retVal);
case RegistryValueKind.String:
case RegistryValueKind.DWord:
case RegistryValueKind.QWord:
Logger.WriteLog("Error opening registry key HKLM\\{0}: {1:x}", registryPath, Marshal.GetLastWin32Error()); classes Registery, RegistryKey 44: RegSetValueEx
Microsoft.Win32.RegistryValueKind dwType,
RegistryValueKind dwType,
My.Computer.Registry.SetValue(KeyName, valueName, value, valueKind)
valueKind as RegistryValueKind If you are getting an HKEY from some source without a managed equivalent, it converts to a .NET RegistryKey as:
RegistryKey regKey = RegistryKey.FromHandle(new SafeRegistryHandle(hKey, true)); Provided you specify true in the SafeRegistryHandle constructor, there is then no need to call RegCloseKey either.
SetValue(Name, Value, RegistryValueKind.Unknown)
Public Sub SetValue(ByVal Name As String, ByVal Value As Object, ByVal RegType As RegistryValueKind)
If RegType = RegistryValueKind.Unknown Then
RegType = RegistryValueKind.String
RegType = RegistryValueKind.DWord
RegType = RegistryValueKind.QWord
RegType = RegistryValueKind.MultiString
RegType = RegistryValueKind.Binary
RegType = RegistryValueKind.String
Case RegistryValueKind.Binary
Case RegistryValueKind.DWord
Case RegistryValueKind.ExpandString
Case RegistryValueKind.MultiString
Case RegistryValueKind.QWord
Case RegistryValueKind.String
Throw New ApplicationException("Registry type of " & RegType & " is not supported")
public bool SetNamedValue(string valName, object value, RegistryValueKind type)
uint retVal = RegOpenKeyEx(HKEY_LOCAL_MACHINE, registryPath, 0, WRITE_FLAG_MASK, out hKey);
case RegistryValueKind.String:
case RegistryValueKind.DWord:
case RegistryValueKind.QWord:
Logger.WriteLog("Error writing value to '{0}\\{1}: 0x{2:x}, return code: {3}", registryPath, valName, Marshal.GetLastWin32Error(), retVal);
Logger.WriteLog("Error opening registry key HKLM\\{0}: {1:x}, return code: {2}", registryPath, Marshal.GetLastWin32Error(), retVal); 45: RegUnLoadKey
Public Shared Sub UnLoadKey(ByVal Key As RegistryKey, ByVal MountPoint As String) RegSaveKey to save registry key to file RegRestoreKey to restore registry key from a file
SE_REGISTRY_KEY,
SE_WMIGUID_OBJECT,S E_REGISTRY_WOW64_32KEY
SE_REGISTRY_KEY,
SE_REGISTRY_WOW64_32KEY 48: Windows Services Can anybody knows how to set the registry key for the current user through windows services in .NET.!
Any body knows how to do this and what Installer Account I can use and can we update the current user registry? Interfaces49: IAutoComplete2
// the registry path, including the value name, where the format 50: ICatRegister
51: IDeskBand
Dim rkClass As RegistryKey = Registry.ClassesRoot.CreateSubKey("CLSID\" & guid)
Dim rkCat As RegistryKey = rkClass.CreateSubKey("Implemented Categories")
Registry.LocalMachine.CreateSubKey("SOFTWARE\Microsoft\Internet Explorer\Toolbar").SetValue(guid, name)
Registry.LocalMachine.CreateSubKey("SOFTWARE\Microsoft\Internet Explorer\Toolbar").DeleteValue(guid, False)
Registry.ClassesRoot.CreateSubKey("CLSID").DeleteSubKeyTree(guid) 52: IDeskBand2
Dim rkClass As RegistryKey = Registry.ClassesRoot.CreateSubKey("CLSID\" & guid)
Dim rkCat As RegistryKey = rkClass.CreateSubKey("Implemented Categories")
Registry.LocalMachine.CreateSubKey("SOFTWARE\Microsoft\Internet Explorer\Toolbar").SetValue(guid, name)
Registry.LocalMachine.CreateSubKey("SOFTWARE\Microsoft\Internet Explorer\Toolbar").DeleteValue(guid, False)
Registry.ClassesRoot.CreateSubKey("CLSID").DeleteSubKeyTree(guid) 53: IFilter
//IOLECommandTarget is registered in the registry Constants55: NERR_
/// <summary> 2611 - Service failed to start due to bad startup information in the registry. </summary>
public const int RplBadRegistry = 2611; 56: PERCEIVED
///<summary>The perceived type was determined through an association in the registry.</summary>
'''<summary>The perceived type was determined through an association in the registry.</summary> 57: PROPERTYKEY
// These PKEYs correspond to registry values under the device class GUID key 58: WINERROR
/// The configuration registry database is corrupt.
/// The configuration registry key is invalid.
/// The configuration registry key could not be opened.
/// The configuration registry key could not be read.
/// The configuration registry key could not be written.
/// One of the files in the registry database had to be recovered by use of a log or alternate copy. The recovery was successful.
public const int ERROR_REGISTRY_RECOVERED = 1014;
/// The registry is corrupted. The structure of one of the files containing registry data is corrupted, or the system's memory image of the file is corrupted, or the file could not be recovered because the alternate copy or log was absent or corrupted.
public const int ERROR_REGISTRY_CORRUPT = 1015;
/// An I/O operation initiated by the registry failed unrecoverably. The registry could not read in, or write out, or flush, one of the files that contain the system's image of the registry.
public const int ERROR_REGISTRY_IO_FAILED = 1016;
/// The system has attempted to load or restore a file into the registry, but the specified file is not in a registry file format.
public const int ERROR_NOT_REGISTRY_FILE = 1017;
/// Illegal operation attempted on a registry key that has been marked for deletion.
/// System could not allocate the required space in a registry log.
/// Cannot create a symbolic link in a registry key that already has subkeys or values.
/// The transaction state of a registry subtree is incompatible with the requested operation.
/// A registry key for event logging could not be created for this session.
/// The directory configuration parameter is missing from the registry.
/// Use the registry database to provide the requested information
/// Could not read key from registry
/// Could not read key from registry
/// Could not write key to registry
/// Could not find the key in the registry
/// Invalid value for registry
/// Use the registry database to provide the requested information
/// Error accessing the OLE registry.
public const int TYPE_E_REGISTRYACCESS = (int)(0x8002801C - 0x100000000);
/// The requested device registry key does not exist.
/// The class installer registry entry is invalid.
/// The property page provider registry entry is invalid.
/// Registry startup information is missing or invalid.
/// An ATR obtained from the registry is not a valid ATR string.
public const int COMADMIN_E_NOREGISTRYCLSID = (int)(0x80110411 - 0x100000000);
public const int COMADMIN_E_BADREGISTRYPROGID = (int)(0x80110412 - 0x100000000);
public const int COMADMIN_E_BADREGISTRYLIBID = (int)(0x8011041E - 0x100000000);
/// Object was not found in registry
public const int COMADMIN_E_NOTINREGISTRY = (int)(0x8011043E - 0x100000000);
/// The COM+ registry database has not been initialized
/// The COM+ registry database is not open
/// The COM+ registry database detected a system error
/// The COM+ registry database is already running
/// This version of the COM+ registry database cannot be migrated
/// The schema version to be migrated could not be found in the COM+ registry database
/// The specified user cannot write to the system registry
public const int COMADMIN_E_REGISTRY_ACCESSDENIED = (int)(0x80110823 - 0x100000000); Structures
/// Log on, then load the user's profile in the HKEY_USERS registry key. The function
/// HKEY_CURRENT_USER registry key. 60: PRINTER_INFO_9
/// The DEVMODE is stored in the user's registry. Cut off search results after 60. Please refine your search. |