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
);


hKey lpSubKey lpClass dwOptions
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.
samDesired lpSecurityAttributes phkResult lpdwDisposition
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

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
);
hKey lpValueName 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.

lpData cbData Retorna ERROR_SUCCESS si todo ha ido bien.
RegSetValueExW (Unicode) and RegSetValueExA (ANSI)

RegGetValue

Devuelve el tipo y el valor de una variable de registro
LONG 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.
ValorSignificado
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.
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.

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]