检查密钥是否已存在(RegOpenKey)

时间:2013-10-25 00:58:49

标签: c++ winapi registry

我这样做了:

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

现在我想要这样做:

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

我需要做什么功能呢?因为如果没有,我将创建一个已经存在的密钥。如果我能避免它会很棒。

1 个答案:

答案 0 :(得分:1)

使用RegCreateKeyEx。如果密钥已经存在,它将打开密钥,如果不存在则创建密钥。 lpdwDisposition参数告诉您实际发生了这两种效果中的哪一种。例如:

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