Rover12421's Blog

The End.

添加注册操作函数修正

今天在使用上次写的 添加删除注册表操作 时,发现了一些错误,原来的函数添加非字符串字段的时候会出现错误。RegSetValueEx 函数设置键值使用的是BYTE类型,需要传递BYTE类型的长度,以前是在这个函数里计算的,但是对DWORD计算会不正确,所以这次修改,直接在添加操作的函数里提供。并且这次还修改了注册表值类型,把原int修改为了DWORD,注册表项值也由LPCTSTR改成了LPBYTE,以增强和原函数类型的对应。修改后的如下:

RegisterOperate.h
  1. #pragma once
  2. #include
  3. #include
  4. #include
  5.  
  6. #pragma comment(lib, "Advapi32.lib")
  7.  
  8. BOOL fnWriteRegSubKey(HKEY hKeyRoot, LPCTSTR lpszSubSection, LPCTSTR lpszEntry, DWORD dwValueType, LPBYTE lpValueData, DWORD dwSize);
  9. BOOL fnDeleteRegSubKey(HKEY hKeyRoot, LPCTSTR lpSubKey);

 

pragma comment(lib, “Advapi32.lib”)

添加这就,是因为静态链接需要。如果没有这句,会报LINK2001错误。

RegisterOperate.cpp
  1. #include "stdafx.h"
  2. #include "RegisterOperate.h"
  3.  
  4.  
  5. BOOL fnWriteRegSubKey(HKEY hKeyRoot, LPCTSTR lpszSubSection, LPCTSTR lpszEntry, DWORD dwValueType, LPBYTE lpValueData, DWORD dwSize)
  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, dwValueType, lpValueData, dwSize);
  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. }

Comments