Alessandra Santos
Alessandra Santos

Reputation: 39

Check if the key already exists (RegOpenKey)

I did this:

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    HKEY CH;

    if(RegCreateKey(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run",&CH) != 0)
    {
        printf("Erro - RegCreateKey\n");
        system("PAUSE");
        return -1;
   }
    if(RegOpenKey(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run",&CH) != 0) // Abre a CH "Minha CH"
    {
        printf("Erro - RegOpenKey\n");
        system("PAUSE");
        return -1;
    }
    if(RegSetValueEx(CH,L"PROC",0,REG_SZ,(LPBYTE) L"C:\\pasta1\\pasta2\\txt.txt",200) != 0)
        printf("Erro - RegSetValue\n");
    RegCloseKey(CH);
    printf("\nsucesso !\n");
    system("PAUSE");
    return 0;
     system("PAUSE");
}

Now I want do it:

 if(key already exist) {
            //don't make nothing 
} else
     Create key
      ... 

What the function that I need to do it ? Because if not, I ever gonna create a key that already exist. And if I can avoid it would be great.

Upvotes: 4

Views: 7060

Answers (1)

Igor Tandetnik
Igor Tandetnik

Reputation: 52471

Use RegCreateKeyEx. It opens the key if it already exists, and creates it if it doesn't. lpdwDisposition parameter tells you which of these two effects actually happened. For example:

DWORD disposition = 0;
RegCreateKeyEx(..., &disposition);
if (disposition == REG_CREATED_NEW_KEY) {
    /* new key was created */
} else {
    /* existing key was opened */
} 

Upvotes: 2

Related Questions