【C】删除含有子KEY的KEY(WIN32API)
DWORD RegDeleteKeys(HKEY RootKey, const char *pSubKey, bool InitVar){
HKEY hKey;
DWORD nRet,NameCnt,NameMaxLen,KeyCnt,KeyMaxLen,MaxDateLen;
static int dwDeep = -1;
if(InitVar)
dwDeep = -1;
else
dwDeep++;
nRet=RegOpenKeyEx(RootKey,pSubKey,0,KEY_ALL_ACCESS,&hKey);
if(nRet!=ERROR_SUCCESS)
{
return 0;
}
nRet = RegQueryInfoKey(hKey,NULL,NULL,NULL,&KeyCnt,&KeyMaxLen,NULL,&NameCnt,&NameMaxLen,&MaxDateLen,NULL,NULL);
if(nRet == ERROR_SUCCESS)
{
for(int dwIndex = KeyCnt - 1; dwIndex >= 0; dwIndex--)//枚举键值
{
char sKeyName = {0}, pSubKeyTemp = {0};
RegEnumKey(hKey, dwIndex, sKeyName, sizeof(sKeyName));
HKEY hKeySub;
DWORD KeyCntSub;
strcpy(pSubKeyTemp, pSubKey);
strcat(pSubKeyTemp, "\\");
strcat(pSubKeyTemp, sKeyName);
nRet = RegOpenKeyEx(RootKey,pSubKeyTemp,0,KEY_ALL_ACCESS,&hKeySub);
if(nRet == ERROR_SUCCESS)
{
nRet = RegQueryInfoKey(hKeySub,NULL,NULL,NULL,&KeyCntSub,&KeyMaxLen,NULL,&NameCnt,&NameMaxLen,&MaxDateLen,NULL,NULL);
if(nRet == ERROR_SUCCESS)
{
if (KeyCntSub != 0)
{
RegDeleteKeys(RootKey, pSubKeyTemp,0);
}
RegCloseKey(hKeySub);
}
}
RegDeleteKey(RootKey ,pSubKeyTemp);
}
RegCloseKey(hKey);
}
RegDeleteKey(RootKey ,pSubKey);
return 0;
}测试:RegDeleteKeys(HKEY_LOCAL_MACHINE,"SYSTEM\\ControlSet001\\services\\WIN64AST",1);
RegDeleteKeys(HKEY_LOCAL_MACHINE,"SYSTEM\\ControlSet002\\services\\WIN64AST",1); 这是递归方式实现的。
不过,在删到一半的时候,如果有别的进程打开了注册表往你要删除的注册表项里创建了新的项,会出错吗? Vista之后有个新API函数 RegDeleteTree 就自带删除带子级的Key。Win2000和XP还有个 SHDeleteKey 函数也能实现类似功能,只不过这个需要单独链接 shlwapi 库。
页:
[1]