也许有时会需要删除注册表的某一项(比如在卸载程序的时候)
因为要删除一项注册表项需要这一项的子项都被删除才能删除成功,所以在实际操作中需要递归遍历要删除的这项注册表是否有子项
我这里就从MFC中提取了相关的处理。
以下是代码:
//*************************************************************
//
// RegDelnodeRecurse()
//
// Purpose: Deletes a registry key and all its subkeys / values.
//
// Parameters: hKeyRoot - Root key
// lpSubKey - SubKey to delete
//
// Return: TRUE if successful.
// FALSE if an error occurs.
//
//*************************************************************
BOOL RegDelnodeRecurseW (HKEY hKeyRoot, LPWSTR lpSubKey)
{
LPWSTR lpEnd;
LONG lResult;
DWORD dwSize;
WCHAR szName[MAX_PATH];
HKEY hKey;
FILETIME ftWrite;
// First, see if we can delete the key without having
// to recurse.
lResult = RegDeleteKeyW(hKeyRoot, lpSubKey);
if (lResult == ERROR_SUCCESS)
return TRUE;
lResult = RegOpenKeyExW (hKeyRoot, lpSubKey, 0, KEY_READ, &hKey);
if (lResult != ERROR_SUCCESS)
{
if (lResult == ERROR_FILE_NOT_FOUND) {
wprintf(L"Key not found.\n");
return TRUE;
}
else {
wprintf(L"Error opening key.\n");
return FALSE;
}
}
// Check for an ending slash and add one if it is missing.
lpEnd = lpSubKey + lstrlenW(lpSubKey);
if (*(lpEnd - 1) != L'\\')
{
*lpEnd = L'\\';
lpEnd++;
*lpEnd = L'\0';
}
// Enumerate the keys
dwSize = MAX_PATH;
lResult = RegEnumKeyExW(hKey, 0, szName, &dwSize, NULL,
NULL, NULL, &ftWrite);
if (lResult == ERROR_SUCCESS)
{
do {
*lpEnd = L'\0';
StringCchCatW(lpSubKey, MAX_PATH * 2, szName);
if (!RegDelnodeRecurseW(hKeyRoot, lpSubKey)) {
break;
}
dwSize = MAX_PATH;
lResult = RegEnumKeyExW(hKey, 0, szName, &dwSize, NULL,
NULL, NULL, &ftWrite);
} while (lResult == ERROR_SUCCESS);
}
lpEnd--;
*lpEnd = L'\0';
RegCloseKey (hKey);
// Try again to delete the key.
lResult = RegDeleteKeyW(hKeyRoot, lpSubKey);
if (lResult == ERROR_SUCCESS)
return TRUE;
return FALSE;
}
//*************************************************************
//
// RegDelnode()
//
// Purpose: Deletes a registry key and all its subkeys / values.
//
// Parameters: hKeyRoot - Root key
// lpSubKey - SubKey to delete
//
// Return: TRUE if successful.
// FALSE if an error occurs.
//
//*************************************************************
BOOL RegDelnodeW (HKEY hKeyRoot, LPWSTR lpSubKey)
{
WCHAR szDelKey[MAX_PATH*2];
StringCchCopyW (szDelKey, MAX_PATH*2, lpSubKey);
return RegDelnodeRecurseW(hKeyRoot, szDelKey);
}
用法:
bool bResult = FALSE;
bResult = RegDelnodeW(HKEY_CLASSES_ROOT, L"users");
结果就是HKEY_CLASSES_ROOT下的users整个被删除。