Leer y escribir el registro de Windows usando WinAPI

 C Programming >> Programación C >  >> Tags >> API
Leer y escribir el registro de Windows usando WinAPI

Si usted es el desarrollador de aplicaciones o controladores de Windows, es posible que necesite acceder al registro de Windows. En este artículo, describiré la forma de crear y acceder a la clave en el registro de Windows. Aquí, asumo que está familiarizado con las partes internas de Windows y la API. Si no está familiarizado con Windows Internal y API, vea este popular curso:Windows Internals

A continuación, encontrará la lista de algunas WinAPI que estoy usando para crear y acceder a la clave de registro de Windows:
  • RegOpenKeyEx
  • RegCreateKeyEx
  • ValorConjuntoRegistroEx
  • RegQueryValueEx
  • Clave de cierre del registro

Puede encontrar aquí una lista completa de funciones de registro:MSDN.

Nota: Para acceder al registro de Windows debe tener derechos de administrador.

Antes de crear la clave, debemos comprender las colmenas del registro de Windows. Las colmenas son el grupo de claves de registro, subclave y valores de registro.

Puede ver las colmenas de registro en el editor de registro en el lado izquierdo de la pantalla. Puede abrir el editor de registro para ejecutar el comando regedit en el cuadro de búsqueda o en la ventana Ejecutar.

Aquí hay una lista de algunas secciones de registro comunes en Windows:
  • HKEY_CLASSES_ROOT
  • HKEY_CURRENT_USER
  • HKEY_LOCAL_MACHINE
  • HKEY_USUARIOS
  • HKEY_CURRENT_CONFIG

Creo que ahora es el momento de ver el código de ejemplo. En este código de ejemplo, crearé una clave y leeré/escribiré el valor.

Cómo crear una clave debajo de las colmenas:

En este código, solo necesita pasar las secciones de registro y el nombre de la clave que desea crear. Si todo está bien, esta función crea la clave debajo de las colmenas dadas.

BOOL CreateRegistryKey(HKEY hKeyParent,PWCHAR subkey)
{
    DWORD dwDisposition; //It verify new key is created or open existing key
    HKEY  hKey;
    DWORD Ret;


    Ret =
        RegCreateKeyEx(
            hKeyParent,
            subkey,
            0,
            NULL,
            REG_OPTION_NON_VOLATILE,
            KEY_ALL_ACCESS,
            NULL,
            &hKey,
            &dwDisposition);

    if (Ret != ERROR_SUCCESS)
    {
        printf("Error opening or creating new key\n");
        return FALSE;
    }

    RegCloseKey(hKey); //close the key
    return TRUE;
}

Escribe un valor DWORD en la clave creada:

En esta función, debe pasar el nombre de las colmenas, el nombre de la clave, el nombre del valor y el valor DWORD que desea almacenar en la clave. En esta función, abro la tecla y solo escribo el valor. Si todo está bien, el valor se almacenará en el registro.

BOOL WriteInRegistry(HKEY hKeyParent, PWCHAR subkey, PWCHAR valueName,DWORD data)
{
    DWORD Ret; //use to check status
    HKEY hKey; //key


    //Open the key
    Ret = RegOpenKeyEx(
              hKeyParent,
              subkey,
              0,
              KEY_WRITE,
              &hKey
          );

    if (Ret == ERROR_SUCCESS)
    {

        //Set the value in key
        if (ERROR_SUCCESS !=
                RegSetValueEx(
                    hKey,
                    valueName,
                    0,
                    REG_DWORD,
                    reinterpret_cast<BYTE *>(&data),
                    sizeof(data)))
        {
            RegCloseKey(hKey);
            return FALSE;
        }

        //close the key
        RegCloseKey(hKey);

        return TRUE;
    }

    return FALSE;
}

Si te encantan los cursos en línea, aquí tienes un buen curso de lengua c para ti de Pluralsight, la prueba de 10 días es gratuita.

Escribe una cadena en la clave creada:

En esta función, debe pasar el nombre de las colmenas, el nombre de la clave, el nombre del valor y la cadena que desea almacenar en la clave. Aquí, una cosa es recordar que el tamaño del carácter ancho es de 16 bits, por lo que debe tener cuidado antes de escribir la cadena en el registro de Windows.

BOOL writeStringInRegistry(HKEY hKeyParent, PWCHAR subkey, PWCHAR valueName, PWCHAR strData)
{
    DWORD Ret;
    HKEY hKey;

    //Check if the registry exists
    Ret = RegOpenKeyEx(
              hKeyParent,
              subkey,
              0,
              KEY_WRITE,
              &hKey
          );

    if (Ret == ERROR_SUCCESS)
    {
        if (ERROR_SUCCESS !=
                RegSetValueEx(
                    hKey,
                    valueName,
                    0,
                    REG_SZ,
                    (LPBYTE)(strData),
                    ((((DWORD)lstrlen(strData) + 1)) * 2)))
        {
            RegCloseKey(hKey);
            return FALSE;
        }

        RegCloseKey(hKey);
        return TRUE;
    }

    return FALSE;
}

Lea un valor DWORD de la clave creada:

Antes de leer el valor de una clave, primero debe abrirla. Necesita el nombre de las colmenas, el nombre de la clave y el nombre del valor para leer el DWORD.

BOOL readDwordValueRegistry(HKEY hKeyParent, PWCHAR subkey, PWCHAR valueName, DWORD *readData)
{

    HKEY hKey;
    DWORD Ret;

    //Check if the registry exists
    Ret = RegOpenKeyEx(
              hKeyParent,
              subkey,
              0,
              KEY_READ,
              &hKey
          );

    if (Ret == ERROR_SUCCESS)
    {

        DWORD data;
        DWORD len = sizeof(DWORD);//size of data

        Ret = RegQueryValueEx(
                  hKey,
                  valueName,
                  NULL,
                  NULL,
                  (LPBYTE)(&data),
                  &len
              );

        if (Ret == ERROR_SUCCESS)
        {
            RegCloseKey(hKey);
            (*readData) = data;
            return TRUE;
        }

        RegCloseKey(hKey);
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

Leer una cadena de la clave creada:

Similar al método anterior. Necesita el nombre de las colmenas, el nombre de la clave y el nombre del valor para leer la cadena de la clave. Antes de leer la cadena, debe proporcionar la longitud adecuada de la cadena o obtendrá un error.

BOOL readStringFromRegistry(HKEY hKeyParent, PWCHAR subkey, PWCHAR valueName, PWCHAR *readData)
{
    HKEY hKey;
    DWORD len = TOTAL_BYTES_READ;

    DWORD readDataLen = len;

    PWCHAR readBuffer = (PWCHAR )malloc(sizeof(PWCHAR)* len);
    if (readBuffer == NULL)
        return FALSE;

    //Check if the registry exists
    DWORD Ret = RegOpenKeyEx(
                    hKeyParent,
                    subkey,
                    0,
                    KEY_READ,
                    &hKey
                );

    if (Ret == ERROR_SUCCESS)
    {

        Ret = RegQueryValueEx(
                  hKey,
                  valueName,
                  NULL,
                  NULL,
                  (BYTE*)readBuffer,
                  &readDataLen
              );

        while (Ret == ERROR_MORE_DATA)
        {
            // Get a buffer that is big enough.

            len += OFFSET_BYTES;
            readBuffer = (PWCHAR)realloc(readBuffer, len);
            readDataLen = len;

            Ret = RegQueryValueEx(
                      hKey,
                      valueName,
                      NULL,
                      NULL,
                      (BYTE*)readBuffer,
                      &readDataLen
                  );
        }

        if (Ret != ERROR_SUCCESS)
        {
            RegCloseKey(hKey);
            return false;;
        }

        *readData = readBuffer;

        RegCloseKey(hKey);
        return true;
    }
    else
    {
        return false;
    }
}

Para comprender los métodos anteriores, veamos un código de ejemplo. En el siguiente ejemplo, he creado una clave "Aticleworld" y dos valores "fecha" y "Mensaje". Almacenaré y leeré el valor almacenado de la clave utilizando los métodos descritos anteriormente.

#include "stdafx.h"
#include <windows.h>
#include <stdio.h>

#define TOTAL_BYTES_READ    1024
#define OFFSET_BYTES 1024


//Create key in registry
BOOL CreateRegistryKey(HKEY hKeyParent,PWCHAR subkey)
{
    DWORD dwDisposition; //It verify new key is created or open existing key
    HKEY  hKey;
    DWORD Ret;


    Ret =
        RegCreateKeyEx(
            hKeyParent,
            subkey,
            0,
            NULL,
            REG_OPTION_NON_VOLATILE,
            KEY_ALL_ACCESS,
            NULL,
            &hKey,
            &dwDisposition);

    if (Ret != ERROR_SUCCESS)
    {
        printf("Error opening or creating key.\n");
        return FALSE;
    }

    RegCloseKey(hKey);
    return TRUE;
}


//Write data in registry
BOOL WriteDwordInRegistry(HKEY hKeyParent, PWCHAR subkey, PWCHAR valueName,DWORD data)
{
    DWORD Ret;
    HKEY hKey;


    //Open the key
    Ret = RegOpenKeyEx(
              hKeyParent,
              subkey,
              0,
              KEY_WRITE,
              &hKey
          );

    if (Ret == ERROR_SUCCESS)
    {

        //Set the value in key
        if (ERROR_SUCCESS !=
                RegSetValueEx(
                    hKey,
                    valueName,
                    0,
                    REG_DWORD,
                    reinterpret_cast<BYTE *>(&data),
                    sizeof(data)))
        {
            RegCloseKey(hKey);
            return FALSE;
        }

        //close the key
        RegCloseKey(hKey);

        return TRUE;
    }

    return FALSE;
}


//Read data from registry
BOOL readDwordValueRegistry(HKEY hKeyParent, PWCHAR subkey, PWCHAR valueName, DWORD *readData)
{

    HKEY hKey;
    DWORD Ret;

    //Check if the registry exists
    Ret = RegOpenKeyEx(
              hKeyParent,
              subkey,
              0,
              KEY_READ,
              &hKey
          );

    if (Ret == ERROR_SUCCESS)
    {

        DWORD data;
        DWORD len = sizeof(DWORD);//size of data

        Ret = RegQueryValueEx(
                  hKey,
                  valueName,
                  NULL,
                  NULL,
                  (LPBYTE)(&data),
                  &len
              );

        if (Ret == ERROR_SUCCESS)
        {
            RegCloseKey(hKey);
            (*readData) = data;
            return TRUE;
        }

        RegCloseKey(hKey);
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}



//Write range and type into the registry
BOOL writeStringInRegistry(HKEY hKeyParent, PWCHAR subkey, PWCHAR valueName, PWCHAR strData)
{
    DWORD Ret;
    HKEY hKey;

    //Check if the registry exists
    Ret = RegOpenKeyEx(
              hKeyParent,
              subkey,
              0,
              KEY_WRITE,
              &hKey
          );

    if (Ret == ERROR_SUCCESS)
    {
        if (ERROR_SUCCESS !=
                RegSetValueEx(
                    hKey,
                    valueName,
                    0,
                    REG_SZ,
                    (LPBYTE)(strData),
                    ((((DWORD)lstrlen(strData) + 1)) * 2)))
        {
            RegCloseKey(hKey);
            return FALSE;
        }

        RegCloseKey(hKey);
        return TRUE;
    }

    return FALSE;
}

//read customer infromation from the registry
BOOL readUserInfoFromRegistry(HKEY hKeyParent, PWCHAR subkey, PWCHAR valueName, PWCHAR *readData)
{
    HKEY hKey;
    DWORD len = TOTAL_BYTES_READ;

    DWORD readDataLen = len;

    PWCHAR readBuffer = (PWCHAR )malloc(sizeof(PWCHAR)* len);
    if (readBuffer == NULL)
        return FALSE;

    //Check if the registry exists
    DWORD Ret = RegOpenKeyEx(
                    hKeyParent,
                    subkey,
                    0,
                    KEY_READ,
                    &hKey
                );

    if (Ret == ERROR_SUCCESS)
    {

        Ret = RegQueryValueEx(
                  hKey,
                  valueName,
                  NULL,
                  NULL,
                  (BYTE*)readBuffer,
                  &readDataLen
              );

        while (Ret == ERROR_MORE_DATA)
        {
            // Get a buffer that is big enough.

            len += OFFSET_BYTES;
            readBuffer = (PWCHAR)realloc(readBuffer, len);
            readDataLen = len;

            Ret = RegQueryValueEx(
                      hKey,
                      valueName,
                      NULL,
                      NULL,
                      (BYTE*)readBuffer,
                      &readDataLen
                  );
        }

        if (Ret != ERROR_SUCCESS)
        {
            RegCloseKey(hKey);
            return false;;
        }

        *readData = readBuffer;

        RegCloseKey(hKey);
        return true;
    }
    else
    {
        return false;
    }
}

//main function
int _tmain(int argc, _TCHAR* argv[])
{
    BOOL status;
    DWORD readData;
    PWCHAR readMessage = nullptr;

    status = CreateRegistryKey(HKEY_CURRENT_USER, L"Aticleworld"); //create key
    if (status != TRUE)
        return FALSE;

    status = WriteDwordInRegistry(HKEY_CURRENT_USER, L"Aticleworld",L"date",12082016); //write dword
    if (status != TRUE)
        return FALSE;

    status = readDwordValueRegistry(HKEY_CURRENT_USER, L"Aticleworld", L"date", &readData); //read dword
    if (status != TRUE)
        return FALSE;

    printf("%ld", readData);

    status = writeStringInRegistry(HKEY_CURRENT_USER, L"Aticleworld", L"Message", L"Happy"); //write string
    if (status != TRUE)
        return FALSE;

    status = readUserInfoFromRegistry(HKEY_CURRENT_USER, L"Aticleworld", L"Message", &readMessage); //read string
    if (status != TRUE)
        return FALSE;

    if (readMessage != nullptr)
    {
        printf(" Message = %S\n", readMessage);
        free(readMessage);
        readMessage = nullptr;
    }

    return 0;
}

  • Los 5 mejores libros C.
  • Obtenga el PUERTO COM del dispositivo serie USB usando el VID y el PID.
  • Programación de puerto serie usando API Win32.
  • Instalar el monitor de puerto de forma silenciosa sin interacción del usuario.
  • Preguntas de la entrevista de C++ con respuestas.
  • Preguntas de la entrevista de C-Sharp.
  • Preguntas de entrevista de Python con respuesta.
  • Diseño de memoria en C.
  • Preguntas de la entrevista de 100 C, su entrevistador podría preguntar.
  • C Preguntas de entrevista para la experiencia.
  • 10 preguntas sobre la asignación de memoria dinámica
  • Manejo de archivos en C, en pocas horas.