parent nodes: CPlusPlusApuntesC
RegistroWindows
Escribir y leer del RegistroWindows
Author: César TM
Date: Oct/2009
Fuente: http://msdn.microsoft.com/en-us/library/ms724844%28VS.85%29.aspx
RegCreateKeyEx
LONG WINAPI RegCreateKeyEx(
__in HKEY hKey,
__in LPCTSTR lpSubKey,
__reserved DWORD Reserved, // must be zero
__in_opt LPTSTR lpClass,
__in DWORD dwOptions,
__in REGSAM samDesired,
__in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes,
__out PHKEY phkResult,
__out_opt LPDWORD lpdwDisposition
);
hKeyUn handle a un registro abierto. Devuelto por RegCreateKeyEx o RegOpenKeyEx, o alguno de los predefinidos:HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS
lpSubKeyEl nombre de la subclave que esta función abre (si existe) o crea (si no existe). Debe ser una subclave de la clave hKey y puede contener hasta 32 niveles en el árbol de registro.
lpClassEl tipo de clase definido por el usuario para esta clave. Este parámetro es opcional, puede ignorarse y ponerse a NULL.
dwOptionsUno de los siguientes valores:
| Valor | Significado |
| REG_OPTION_BACKUP_RESTORE | Se ignora el parámetro samDesired y se intenta abrir la clave con el aceso necesario para hacer backup/restore de la clave. If the calling thread has the SE_BACKUP_NAME privilege enabled, the key is opened with the ACCESS_SYSTEM_SECURITY and KEY_READ access rights. If the calling thread has the SE_RESTORE_NAME privilege enabled, the key is opened with the ACCESS_SYSTEM_SECURITY and KEY_WRITE access rights. If both privileges are enabled, the key has the combined access rights for both privileges. For more information, see Running with Special Privileges. |
| REG_OPTION_CREATE_LINK | This key is a symbolic link. The target path is assigned to the L"SymbolicLinkValue" value of the key. The target path must be an absolute registry path. Registry symbolic links should be used only when absolutely necessary for application compatibility. |
| REG_OPTION_NON_VOLATILE | La clave es no volátil. Este es el valor por defecto. La información se almacena en un archivo y es preservada cuando el sistema se restaura. La función RegSaveKey guarda las claves que son no volátiles. |
| REG_OPTION_VOLATILE | La clave es volátil. La información es almacenada en memoria y no es preservada cuando el registro correspondiente es unloaded. Para HKEY_LOCAL_MACHINE, sería cuando el sistema se apaga. Para otras claves cargadas con con la función RegLoadKey ocurre cuando se llama a RegUnLoadKey. La función RegSaveKey no guarda claves volátiles. Este parámetro es ignorado para claves que ya existen. |
samDesiredUna máscara con los derechos de aceso de la clave. Por ejemplo KEY_ALL_ACCESS
lpSecurityAttributesParámetro opcional. Un apuntador a una estructura SECURITY_ATTRIBUTES que determina si el handle de retorno puede ser heredable por los procesos hijos o no. Sí es NULL no puede ser heredado.
phkResultUn apuntador a una variable que reciba el handle a la clave creada/abierta. Se usará para cerrarla clave después de haberla usado, mediante la función RegCloseKey.
lpdwDispositionEs un parámetro opcional, es un apuntador (o NULL ) a una variable para guardar la información siguiente (si se pasa NULL no se obtendrá ninguna información):
| valor | significado |
| REG_CREATED_NEW_KEY | La clave no existía y ha sido creada. |
| REG_OPENED_EXISTING_KEY | La clave existía y ha sido abierta sin cambiarla. |
Valor de retorno
Si tiene éxito el valor será ERROR_SUCCESS. Si falla será un valor de error distinto de cero definido en Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.
Notas
La clave se abre o crea sin valores. Para oner los valores hay que usar la función RegSetValueEx
No se puede crear claves como hijos inmediatamente bajo HKEY_USERS o HKEY_LOCAL_MACHINE
RegCreateKeyExW (Unicode) and RegCreateKeyExA (ANSI)
RegSetValueEx
Sets the data and type of a specified value under a registry key.
LONG WINAPI RegSetValueEx(
__in HKEY hKey,
__in_opt LPCTSTR lpValueName,
__reserved DWORD Reserved, // must be zero
__in DWORD dwType,
__in_opt const BYTE *lpData,
__in DWORD cbData
);
hKeyhandle a la clave abierta
lpValueNameEl nombre del valor a fijar. Si no existe lo creará. Si es NULL o "" se creará un valor de tipo unnammed que puede ser de cualquier tipo.
dwType
| Valor | Tipo |
| REG_BINARY | Binary data in any form. |
| REG_DWORD | A 32-bit number. |
| REG_DWORD_LITTLE_ENDIAN | A 32-bit number in little-endian format. Windows is designed to run on little-endian computer architectures. Therefore, this value is defined as REG_DWORD in the Windows header files. |
| REG_DWORD_BIG_ENDIAN | A 32-bit number in big-endian format. Some UNIX systems support big-endian architectures. |
| REG_EXPAND_SZ | A null-terminated string that contains unexpanded references to environment variables (for example, "%PATH%"). It will be a Unicode or ANSI string depending on whether you use the Unicode or ANSI functions. To expand the environment variable references, use the ExpandEnvironmentStrings function. |
| REG_LINK | A null-terminated Unicode string that contains the target path of a symbolic link that was created by calling the RegCreateKeyEx function with REG_OPTION_CREATE_LINK. |
| REG_MULTI_SZ | A sequence of null-terminated strings, terminated by an empty string (0). The following is an example: String10String20String30LastString00 The first 0 terminates the first string, the second to the last 0 terminates the last string, and the final 0 terminates the sequence. Note that the final terminator must be factored into the length of the string. |
| REG_NONE | No defined value type. |
| REG_QWORD | A 64-bit number. |
| REG_QWORD_LITTLE_ENDIAN | A 64-bit number in little-endian format. Windows is designed to run on little-endian computer architectures. Therefore, this value is defined as REG_QWORD in the Windows header files. |
| REG_SZ | A null-terminated string. This will be either a Unicode or an ANSI string, depending on whether you use the Unicode or ANSI functions. |
String Values
If data has the REG_SZ, REG_MULTI_SZ, or REG_EXPAND_SZ type, the string may not have been stored with the proper terminating null characters. Therefore, when reading a string from the registry, you must ensure that the string is properly terminated before using it; otherwise, it may overwrite a buffer. (Note that REG_MULTI_SZ strings should have two terminating null characters.)
When writing a string to the registry, you must specify the length of the string, including the terminating null character (0). A common error is to use the strlen function to determine the length of the string, but to forget that strlen returns only the number of characters in the string, not including the terminating null. Therefore, the length of the string should be calculated as follows: strlen( string ) + 1
A REG_MULTI_SZ string ends with a string of length 0. Therefore, it is not possible to include a zero-length string in the sequence. An empty sequence would be defined as follows: 0.
lpDataThe data to be stored. For string-based types, such as REG_SZ, the string must be null-terminated. With the REG_MULTI_SZ data type, the string must be terminated with two null characters.
cbDataThe size of the information pointed to by the lpData parameter, in bytes. If the data is of type REG_SZ, REG_EXPAND_SZ, or REG_MULTI_SZ, cbData must include the size of the terminating null character or characters.
Retorna ERROR_SUCCESS si todo ha ido bien.
RegSetValueExW (Unicode) and RegSetValueExA (ANSI)
RegGetValue
Devuelve el tipo y el valor de una variable de registroLONG WINAPI RegGetValue(
__in HKEY hkey,
__in_opt LPCTSTR lpSubKey,
__in_opt LPCTSTR lpValue,
__in_opt DWORD dwFlags,
__out_opt LPDWORD pdwType,
__out_opt PVOID pvData,
__inout_opt LPDWORD pcbData
);
hKey handle a la clave abierta. Debe estar abierta con permiso KEY_QUERY_VALUE
lpSubKey Nombre de la variable de registro. No es sensible a mayúsculas y es un parámetro opcional.
lpValue Nombre del valor a recuperar.
dwFlags Restricciones de tipo del valor a recuperar, si no se cumplen las restricciones la función falla.
| Valor | Significado |
| RRF_RT_ANY | No type restriction. |
| RRF_RT_DWORD | Restrict type to 32-bit RRF_RT_REG_BINARY, RRF_RT_REG_DWORD. |
| RRF_RT_QWORD | Restrict type to 64-bit RRF_RT_REG_BINARY, RRF_RT_REG_DWORD. |
| RRF_RT_REG_BINARY | Restrict type to REG_BINARY. |
| RRF_RT_REG_DWORD | Restrict type to REG_DWORD. |
| RRF_RT_REG_EXPAND_SZ | Restrict type to REG_EXPAND_SZ. |
| RRF_RT_REG_MULTI_SZ | Restrict type to REG_MULTI_SZ. |
| RRF_RT_REG_NONE | Restrict type to REG_NONE. |
| RRF_RT_REG_QWORD | Restrict type to REG_QWORD. |
| RRF_RT_REG_SZ | Restrict type to REG_SZ. |
pdwType Puntero a la variable en la que guardar el código que indica el tipo del dato almacenado. For a list of the possible type codes, see Registry Value Types. This parameter can be NULL if the type is not required.
pvData Apuntador a un buffer que recibirá el dato. This parameter can be NULL if the data is not required.
If the data is a string, the function checks for a terminating null character. If one is not found, the string is stored with a null terminator if the buffer is large enough to accommodate the extra character. Otherwise, the function fails and returns ERROR_MORE_DATA.
pcbData A pointer to a variable that specifies the size of the buffer pointed to by the pvData parameter, in bytes. When the function returns, this variable contains the size of the data copied to pvData.
The pcbData parameter can be NULL only if pvData is NULL.
If the data has the REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ type, this size includes any terminating null character or characters. For more information, see Remarks.
If the buffer specified by pvData parameter is not large enough to hold the data, the function returns ERROR_MORE_DATA and stores the required buffer size in the variable pointed to by pcbData. In this case, the contents of the pvData buffer are undefined.
If pvData is NULL, and pcbData is non-NULL, the function returns ERROR_SUCCESS and stores the size of the data, in bytes, in the variable pointed to by pcbData. This enables an application to determine the best way to allocate a buffer for the value's data.
If hKey specifies HKEY_PERFORMANCE_DATA and the pvData buffer is not large enough to contain all of the returned data, the function returns ERROR_MORE_DATA and the value returned through the pcbData parameter is undefined. This is because the size of the performance data can change from one call to the next. In this case, you must increase the buffer size and call RegGetValue again passing the updated buffer size in the pcbData parameter. Repeat this until the function succeeds. You need to maintain a separate variable to keep track of the buffer size, because the value returned by pcbData is unpredictable.
Leer de registro
no consigo que funcione// Lee un long del registro
__declspec(dllexport) BOOL LeeDeGeneralRegistro( CString & nombre, long & resultado )
{
/* HKEY hResult;
LONG lRetVal;
// abre la subclave, si no existe la crea
char szSubKey[] = _T( "Software\\IN\\Colegio\\General" );
lRetVal = RegCreateKeyEx( HKEY_CURRENT_USER, szSubKey, 0, "", REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hResult, NULL );
if( lRetVal != ERROR_SUCCESS )
{ // error al abrir o crear la clave
#ifdef _DEBUG
::MessageBox( NULL, _T("error LeeDeGeneralRegistro, RegCreateKeyEx"), _T("error LeeDeGeneralRegistro, RegCreateKeyEx"), MB_OK );
#endif
return FALSE;
}
// abierta o creada con éxito
// da formato adecuado a nombre y valor. Valor debe acabar en '\0'.
char * szNombre = nombre.GetBuffer( nombre.GetLength() );
//const unsigned char * lpData = reinterpret_cast< const unsigned char * >( &valor );
long size = sizeof( resultado );
lRetVal = RegGetValueEx( hResult, szSubKey, szNombre, 0, NULL, &resultado, &size );
// __out_opt PVOID pvData,
// __inout_opt LPDWORD pcbData
lRetVal = RegSetValueEx( hResult, szNombre, 0, REG_DWORD, lpData, size );
if( lRetVal != ERROR_SUCCESS )
{ // error al dar valor a la subclave
#ifdef _DEBUG
::MessageBox( NULL, _T("error EscribeEnGeneralRegistro, RegSetValueEx"), _T("error EscribeEnGeneralRegistro, RegSetValueEx"), MB_OK );
#endif
return FALSE;
}
// valor puesto con éxito
// cierra la clave
if( RegCloseKey( hResult ) != ERROR_SUCCESS )
{
#ifdef _DEBUG
::MessageBox( NULL, _T("error EscribeEnGeneralRegistro, RegCloseKey"), _T("error EscribeEnGeneralRegistro, RegCloseKey"), MB_OK );
#endif
return FALSE;
}
*/
// clave cerrada con éxito
return TRUE;
}
Esta función la hice pero no la puedo usar así que he de borrarla, la copio aquí para tenerla en el futuro.// Escribe una cadena no unicode en el registro
__declspec(dllexport) BOOL EscribeEnGeneralRegistro( CString & nombre , CString & valor )
{
HKEY hResult;
LONG lRetVal;
//DWORD dwDisp;
// abre la subclave, si no existe la crea
char szSubKey[] = _T( "Software\\IN\\Colegio\\General" );
//lRetVal = RegCreateKeyExW( HKEY_CURRENT_USER, ptSubKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hResult, &dwDisp );
lRetVal = RegCreateKeyEx( HKEY_CURRENT_USER, szSubKey, 0, "", REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hResult, NULL );
if( lRetVal == ERROR_SUCCESS ) // abierta o creada con éxito
{
// da formato adecuado a nombre y valor. Valor debe acabar en '\0'.
char * szNombre = nombre.GetBuffer( nombre.GetLength() );
unsigned char * szValor = reinterpret_cast< unsigned char * >( valor.GetBuffer( valor.GetLength() ) );
szValor += '\0';
long size = valor.GetLength() + 1; // +1 para contar también el caracter nulo
lRetVal = RegSetValueEx( hResult, szNombre, 0, REG_SZ, szValor, size );
if( lRetVal != ERROR_SUCCESS )
{ // error
::MessageBox( NULL, _T("error"), _T("error"), MB_OK );
}
}
else
{ // error
::MessageBox( NULL, _T("error"), _T("error"), MB_OK );
}
// close the key.
if( RegCloseKey ( hResult ) != ERROR_SUCCESS )
{
::MessageBox( NULL, _T("error"), _T("error"), MB_OK );
return FALSE;
}
// Success!
return TRUE;
}
Esta es la otra, la que escribe un long en el registro:// Escribe un long en el registro
__declspec(dllexport) BOOL EscribeEnGeneralRegistro( CString & nombre , long valor )
{
HKEY hResult;
LONG lRetVal;
// abre la subclave, si no existe la crea
char szSubKey[] = _T( "Software\\IN\\Colegio\\General" );
lRetVal = RegCreateKeyEx( HKEY_CURRENT_USER, szSubKey, 0, "", REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hResult, NULL );
if( lRetVal == ERROR_SUCCESS ) // abierta o creada con éxito
{
// da formato adecuado a nombre y valor. Valor debe acabar en '\0'.
char * szNombre = nombre.GetBuffer( nombre.GetLength() );
const unsigned char * lpData = reinterpret_cast< const unsigned char * >( &valor );
long size = sizeof( valor );
lRetVal = RegSetValueEx( hResult, szNombre, 0, REG_DWORD, lpData, size );
if( lRetVal != ERROR_SUCCESS )
{ // error
#ifdef _DEBUG
::MessageBox( NULL, _T("error EscribeEnGeneralRegistro, RegSetValueEx"), _T("error EscribeEnGeneralRegistro, RegSetValueEx"), MB_OK );
#endif
return FALSE;
}
}
else
{ // error
#ifdef _DEBUG
::MessageBox( NULL, _T("error EscribeEnGeneralRegistro, RegCreateKeyEx"), _T("error EscribeEnGeneralRegistro, RegCreateKeyEx"), MB_OK );
#endif
return FALSE;
}
// close the key.
if( RegCloseKey( hResult ) != ERROR_SUCCESS )
{
#ifdef _DEBUG
::MessageBox( NULL, _T("error EscribeEnGeneralRegistro, RegCloseKey"), _T("error EscribeEnGeneralRegistro, RegCloseKey"), MB_OK );
#endif
return FALSE;
}
// Success!
return TRUE;
}
_________________________________________________________________________________________________________
CPlusPlusApuntesC [camelCaseWordsEnabled: false]