Rover12421's Blog

The End.

添加删除注册表操作

昨天就整理好了,但是删除子项的时候,只能删除顶级的,不能一次上除所以子项。今天修改完了,同时也发现了一个以前写的小问题,太啰嗦了,在根本不需要RegOpenKeyEx的时候用了它,导致函数有点臃肿,一步能做到的,分成两三步做了。直接贴代码,还是两个文件.

RegisterOperate.h
  1. #pragma once
  2. #include
  3. #include
  4. #include
  5.  
  6. BOOL fnWriteRegSubKey(HKEY hKeyRoot, LPCTSTR lpszSubSection, LPCTSTR lpszEntry, LPCTSTR lpszValue, int nValueType);
  7. BOOL fnDeleteRegSubKey(HKEY hKeyRoot, LPCTSTR lpSubKey);

 

RegisterOperate.cpp
  1. #include "stdafx.h"
  2. #include "RegisterOperate.h"
  3.  
  4.  
  5. BOOL fnWriteRegSubKey(HKEY hKeyRoot, LPCTSTR lpszSubSection, LPCTSTR lpszEntry, LPCTSTR lpszValue, int nValueType)
  6. {
  7.     HKEY hSecKey = NULL;
  8.     DWORD dwDisposition;
  9.  
  10.     RegCreateKeyEx(hKeyRoot, lpszSubSection, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hSecKey, &dwDisposition);
  11.     if (hSecKey == NULL)
  12.     {
  13.         return FALSE;
  14.     }    
  15.  
  16.     LONG hResult = NULL;
  17.     hResult = RegSetValueEx(hSecKey, lpszEntry, NULL, nValueType, (LPBYTE)lpszValue, (lstrlen(lpszValue) + 1) * sizeof(TCHAR));
  18.     RegCloseKey(hSecKey);
  19.     if (hResult != ERROR_SUCCESS)
  20.     {
  21.         return FALSE;
  22.     }
  23.     return TRUE;
  24. }
  25.  
  26. BOOL fnDeleteRegSubKey(HKEY hKeyRoot, LPCTSTR lpSubKey)
  27. {
  28.     HKEY hOpenKey = NULL;
  29.     RegOpenKeyEx(hKeyRoot, lpSubKey, 0, KEY_ALL_ACCESS, &hOpenKey);
  30.     if (!hOpenKey)
  31.     {
  32.         return FALSE;
  33.     }
  34.  
  35.     DWORD dwSize = MAX_PATH;
  36.     FILETIME ftEnumKey;
  37.     TCHAR szName[MAX_PATH*2];
  38.     ZeroMemory(szName, sizeof(szName));
  39.  
  40.     while (ERROR_SUCCESS == RegEnumKeyEx(hOpenKey, 0, szName, &dwSize, NULL, NULL, NULL, &ftEnumKey))
  41.     {
  42.         TCHAR szSubSubKey[MAX_PATH*2];
  43.         ZeroMemory(szSubSubKey, sizeof(szSubSubKey));
  44.         StringCchCopy(szSubSubKey, MAX_PATH*2, lpSubKey);
  45.         StringCchCat(szSubSubKey, MAX_PATH*2, _T("\\"));
  46.         StringCchCat(szSubSubKey, MAX_PATH*2, szName);
  47.         if (!fnDeleteRegSubKey(hKeyRoot, szSubSubKey))
  48.         {
  49.             break;
  50.         }
  51.     }
  52.  
  53.     LONG hResult = NULL;
  54.     hResult = RegDeleteKey(hKeyRoot, lpSubKey);
  55.     if (hResult == ERROR_SUCCESS)
  56.     {
  57.         RegCloseKey(hOpenKey);
  58.         return TRUE;
  59.     }
  60.     RegCloseKey(hOpenKey);
  61.     return FALSE;
  62. }

 

头文件里包含的三个文件还是说下吧。Windows.h,是应为使用了ZeroMemory,习惯用宏了,如果不用宏的话,也可以不包含这个文件。Winreg.h,这个一看也知道是注册表操作的。strsafe.h,这个是使用到了StringCchCopy,StringCchCat两个安全字符串操作函数,如果使用老式的字符串函数也可以不包含的。

Comments