Lettura e scrittura del registro di Windows utilizzando WinAPI

 C Programming >> Programmazione C >  >> Tags >> API
Lettura e scrittura del registro di Windows utilizzando WinAPI

Se sei l'applicazione Windows o lo sviluppatore del driver, potrebbe essere necessario accedere al registro di Windows. In questo articolo, descriverò come creare e accedere alla chiave nel registro di Windows. Qui, presumo che tu abbia familiarità con gli interni e l'API di Windows. Se non hai dimestichezza con Windows Internal e API, guarda questo corso popolare:Windows Internals

Di seguito trovi l'elenco di alcune WinAPI che sto utilizzando per creare e accedere alla chiave di registro di Windows:
  • RegOpenKeyEx
  • RegCreateKeyEx
  • RegSetValueEx
  • RegQueryValueEx
  • RegCloseKey

Puoi trovare qui un elenco completo delle funzioni di registro – MSDN.

Nota: Per accedere al registro di Windows dovresti avere i diritti di amministratore.

Prima di creare la chiave, è necessario comprendere gli alveari del registro di Windows. Gli hive sono il gruppo di chiavi di registro, sottochiave e valori di registro.

Puoi vedere gli alveari del registro nell'editor del registro sul lato sinistro dello schermo. Puoi aprire l'editor del registro per eseguire il comando regedit nella casella di ricerca o nella finestra Esegui.

Ecco un elenco di alcuni hive di registro comuni in Windows:
  • HKEY_CLASSES_ROOT
  • HKEY_CURRENT_USER
  • HKEY_LOCAL_MACHINE
  • HKEY_USERS
  • HKEY_CURRENT_CONFIG

Penso che ora sia il momento di vedere il codice di esempio. In questo codice di esempio creerò una chiave e leggerò/scriverò il valore.

Come creare una chiave sotto gli alveari:

In questo codice, devi solo passare gli hive del registro e il nome della chiave che desideri creare. Se tutto va bene, questa funzione crea la chiave sotto gli alveari dati.

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

Scrivi un valore DWORD nella chiave creata:

In questa funzione, è necessario passare il nome dell'hive, il nome della chiave, il nome del valore e il valore DWORD che si desidera memorizzare nella chiave. In questa funzione, sto aprendo la chiave e scrivo solo il valore. Se tutto va bene, il valore verrà archiviato nel 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;
}

Se ami i corsi online, ecco per te un buon corso di lingua C di Pluralsight, 10 giorni di prova è gratuito.

Scrivi una stringa nella chiave creata:

In questa funzione, è necessario passare il nome dell'hive, il nome della chiave, il nome del valore e la stringa che si desidera memorizzare nella chiave. Qui una cosa è dover ricordare che la dimensione di wide char è 16 bit, quindi è necessario fare attenzione prima di scrivere la stringa nel registro di 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;
}

Leggi un valore DWORD dalla chiave creata:

Prima di leggere il valore da una chiave, dovresti prima aprirla. Per leggere la DWORD sono necessari il nome dell'hive, il nome della chiave e il nome del valore.

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

Leggi una stringa dalla chiave creata:

Simile al metodo sopra. Per leggere la stringa dalla chiave sono necessari il nome dell'hive, il nome della chiave e il nome del valore. Prima di leggere la stringa devi fornire la lunghezza corretta della stringa o riceverai un errore.

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

Per comprendere i metodi precedenti, vediamo un codice di esempio, nell'esempio seguente, ho creato una chiave "Aticleworld" e due valori "data" e "Messaggio". Memorizzerò e leggerò il valore memorizzato dalla chiave utilizzando i metodi sopra descritti.

#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;
}

  • I migliori libri sulle 5 C.
  • Ottieni la PORTA COM del dispositivo seriale USB utilizzando VID e PID.
  • Programmazione della porta seriale utilizzando l'API Win32.
  • Installa il monitor della porta in modo invisibile all'utente senza l'interazione dell'utente.
  • Domande del colloquio C++ con risposte.
  • Domande sull'intervista C-Sharp.
  • Domande per l'intervista Python con risposta.
  • Layout di memoria in C.
  • Domande del colloquio di 100 C, potrebbe chiederti il ​​tuo intervistatore.
  • C Domande per l'intervista per l'esperienza.
  • 10 domande sull'allocazione dinamica della memoria
  • Gestione dei file in C, in poche ore.