注册表操作类

来源:互联网 发布:游戏编程教学视频 编辑:程序博客网 时间:2024/06/05 05:56

在前一篇中,我有提到应用程序关联的方法,归根结底就是在注册表中添加了相应的内容。但这样有个不好的地方,就是会在注册表中留下很多垃圾信息。怎样在调试完程序后,自动清除注册表中冗余的信息呢?我在这里提供一个简单的方法,与大家分享哈。

    (一)跟大家介绍一个c++的注册表操作的封装类

1.注册表项RegEntry.h

[cpp] view plaincopy
  1. // CRegEntry: interface for the CRegEntry class.  
  2. //  
  3. //////////////////////////////////////////////////////////////////////  
  4.   
  5. #if !defined(_REGENTRY_H_INCLUDED)  
  6. #define _REGENTRY_H_INCLUDED  
  7.   
  8. #if _MSC_VER > 1000  
  9. #pragma once  
  10. #endif // _MSC_VER > 1000  
  11.   
  12. class CRegistry;  
  13.   
  14. class CRegEntry  
  15. {  
  16. public:  
  17.   
  18.     CRegEntry(CRegistry* Owner = NULL);       
  19.     virtual ~CRegEntry() { if (lpszName) delete [] lpszName; if (lpszStr) delete [] lpszStr; };  
  20.   
  21.     /* -----------------------------------------* 
  22.      *  Operators                               * 
  23.      * -----------------------------------------*/  
  24.       
  25.     CRegEntry&  operator =( CRegEntry& cregValue );  
  26.     CRegEntry&  operator =( LPCTSTR lpszValue );  
  27.     CRegEntry&  operator =( LPDWORD lpdwValue );      
  28.     CRegEntry&  operator =( DWORD dwValue ) { return (*this = &dwValue); }    
  29.                 operator LPTSTR();  
  30.                 operator DWORD();  
  31.   
  32.       
  33.     // Data types without implemented conversions  
  34.     // NOTE: I realize these will only check asserts  
  35.     // when a value is set and retrieved during the  
  36.     // same session. But it is better than no check.  
  37.   
  38.     REGENTRY_NONCONV_STORAGETYPE(POINT);  
  39.     REGENTRY_NONCONV_STORAGETYPE(RECT);  
  40.   
  41.     // Numeric types with conversions  
  42.     // If you'd like to add more, follow this form:  
  43.     // data type, max string length + 1, format specification, from string, from DWORD  
  44.   
  45.     REGENTRY_CONV_NUMERIC_STORAGETYPE(__int64, 28, %I64d, _ttoi64(lpszStr), (__int64)dwDWORD)  
  46.     REGENTRY_CONV_NUMERIC_STORAGETYPE(double, 18, %f, _tcstod(lpszStr, NULL), (double)dwDWORD)    
  47.     REGENTRY_CONV_NUMERIC_STORAGETYPE(bool, 2, %d, (_ttoi(lpszStr) != 0), (dwDWORD != 0))  
  48.     REGENTRY_CONV_NUMERIC_STORAGETYPE(int, 12, %d, _ttoi(lpszStr), (int)dwDWORD)  
  49.     REGENTRY_CONV_NUMERIC_STORAGETYPE(UINT, 11, %d, (UINT)_tcstoul(lpszStr, NULL, NULL), (UINT)dwDWORD)  
  50.   
  51.     // Types with conversions: type to/from string, type from unsigned long  
  52.   
  53.     REGENTRY_CONV_STORAGETYPE(tstring, _R_BUF(_MAX_REG_VALUE); _tcscpy(buffer, Value.c_str());,  
  54.     lpszStr, _ultot(dwDWORD, lpszStr, NULL), _T(""))  
  55.           
  56.   
  57.     /* -----------------------------------------* 
  58.      *  Member Variables and Functions          * 
  59.      * -----------------------------------------*/  
  60.       
  61.     LPTSTR      lpszName;   // The value name  
  62.     UINT        iType;      // Value data type  
  63.       
  64.     void        InitData(CRegistry* Owner = NULL);    
  65.     void        ForceStr();  
  66.     bool        Delete();     
  67.   
  68.   
  69.     /* The following six functions handle REG_MULTI_SZ support: */  
  70.   
  71.     void        SetMulti(LPCTSTR lpszValue, size_t nLen, bool bInternal = false);     
  72.     void        MultiRemoveAt(size_t nIndex);  
  73.     void        MultiSetAt(size_t nIndex, LPCTSTR lpszVal);  
  74.     LPTSTR      GetMulti(LPTSTR lpszDest, size_t nMax = _MAX_REG_VALUE);  
  75.     LPCTSTR     MultiGetAt(size_t nIndex);    
  76.     size_t      MultiLength(bool bInternal = false);  
  77.     size_t      MultiCount();  
  78.           
  79.   
  80.     void        SetBinary(LPBYTE lpbValue, size_t nLen);      
  81.     void        GetBinary(LPBYTE lpbDest, size_t nMaxLen);  
  82.     size_t      GetBinaryLength();  
  83.     bool        Convertible() { return __bConvertable; }  
  84.   
  85.     __inline    SetOwner(CRegistry* Owner) { __cregOwner = Owner; }  
  86.       
  87.     template <class T>void SetStruct(T &type) { SetBinary((LPBYTE) &type, sizeof(T)); }  
  88.     template <class T>void GetStruct(T &type) { GetBinary((LPBYTE) &type, sizeof(T)); }  
  89.       
  90.     __inline    IsString()      { return (iType == REG_SZ); }  
  91.     __inline    IsDWORD()       { return (iType == REG_DWORD); }  
  92.     __inline    IsBinary()      { return (iType == REG_BINARY); }     
  93.     __inline    IsMultiString() { return (iType == REG_MULTI_SZ); }  
  94.       
  95.     __inline    IsStored()      { return __bStored; }  
  96.     __inline    Exists()        { return __bStored; }  
  97.   
  98.     __inline    MultiClear()    { SetMulti(_T("/0"), 2); }  
  99.     __inline    MultiAdd(LPCTSTR lpszVal) { MultiSetAt(MultiCount(), lpszVal); }  
  100.   
  101. protected:  
  102.   
  103.     CRegistry*  __cregOwner;  
  104.     bool        __bConvertable;  
  105.     bool        __bStored;  
  106.   
  107. private:  
  108.   
  109.     /* Create a variable for each prominent data type */  
  110.   
  111.     DWORD       dwDWORD;      
  112.     LPTSTR      lpszStr;  
  113.           
  114.     std::vector<BYTE> vBytes;  
  115.     std::vector<tstring> vMultiString;  
  116. };  
  117.   
  118.   
  119. #endif  

2.注册表节点Registry.h

[cpp] view plaincopy
  1. #if !defined(_REGISTRY_H_INCLUDED)  
  2. #define _REGISTRY_H_INCLUDED  
  3.   
  4. #if _MSC_VER > 1000  
  5. #pragma once  
  6. #endif // _MSC_VER > 1000  
  7.   
  8. /* Silence STL warnings */  
  9.   
  10. #pragma warning (disable : 4786)  
  11. #pragma warning (disable : 4514)  
  12. #pragma warning (push, 3)  
  13.   
  14. #ifdef _UNICODE  
  15. #if !defined(UNICODE)  
  16. #define UNICODE   
  17. #endif  
  18. #endif  
  19.   
  20. #include <windows.h>  
  21. #include <math.h>  
  22. #include <TCHAR.h>  
  23. #include <stdlib.h>  
  24. #include <stdio.h>  
  25. #include <vector>  
  26. #include <assert.h>  
  27.   
  28.   
  29. /* ==================================== 
  30.  * Begin Preprocessor Definitions 
  31.  * 
  32.  * - Ugly, but well worth it. 
  33.  * ==================================== */  
  34.   
  35.   
  36. #ifdef _UNICODE  
  37. typedef std::wstring tstring;  
  38. #else  
  39. typedef std::string tstring;  
  40. #endif  
  41.   
  42.   
  43. /* CRegistry Open Flags */  
  44.   
  45. #define CREG_CREATE     1  
  46. #define CREG_AUTOOPEN   2  
  47. #define CREG_NOCACHE    4  
  48.   
  49. /* CRegistry Behaivor flags */  
  50.   
  51. #define CREG_LOADING    8  
  52.   
  53.   
  54. #define _MAX_REG_VALUE  2048    // Maximum Value length, this may be increased  
  55.   
  56. #define NOT_ES(func)            func != ERROR_SUCCESS  
  57. #define IS_ES(func)             func == ERROR_SUCCESS  
  58. #define _R_BUF(size)            _TCHAR buffer[size]  
  59.   
  60. #define REGENTRY_AUTO           __cregOwner->GetFlags() & CREG_AUTOOPEN  
  61. #define REGENTRY_TRYCLOSE       if (REGENTRY_AUTO) __cregOwner->AutoClose()  
  62. #define REGENTRY_SZ_SAFE        iType == REG_SZ || iType == REG_BINARY  
  63. #define REGENTRY_ALLOWCONV(b)   __bConvertable = b;  
  64.   
  65.   
  66. #define REGENTRY_REFRESH_IF_NOCACHE /  
  67.     if (__cregOwner->GetFlags() & CREG_NOCACHE && /  
  68.         REGENTRY_NOTLOADING && REGENTRY_KEYVALID( KEY_QUERY_VALUE ))/  
  69.         __cregOwner->Refresh();  
  70.   
  71. #define REGENTRY_UPDATE_MULTISTRING /  
  72.     LPTSTR lpszBuffer = new _TCHAR[_MAX_REG_VALUE]; /  
  73.     REGENTRY_SETLOADING(+); GetMulti(lpszBuffer); REGENTRY_SETLOADING(-); /  
  74.     SetMulti(lpszBuffer, MultiLength(true), true); /  
  75.     delete [] lpszBuffer;  
  76.   
  77.       
  78. #define REGENTRY_KEYVALID(auto_access) /  
  79.     lpszName && ((REGENTRY_AUTO && __cregOwner->AutoOpen(auto_access)) || (!(REGENTRY_AUTO) && __cregOwner->hKey != NULL))  
  80.   
  81. #define REGENTRY_NOTLOADING /  
  82.     !(__cregOwner->GetFlags() & CREG_LOADING)  
  83.   
  84. #define REGENTRY_SETLOADING(op) /  
  85.     __cregOwner->__dwFlags op= CREG_LOADING  
  86.   
  87. #define REGENTRY_BINARYTOSTRING /  
  88.     if (iType == REG_BINARY) { ForceStr(); lpszStr = *this; }   
  89.   
  90. #define REGENTRY_NONCONV_STORAGETYPE(type) /  
  91.     CRegEntry& operator=( type &Value ){ REGENTRY_ALLOWCONV(false) SetStruct(Value); return *this; }  /  
  92.     operator type(){ type Return; GetStruct(Return); return Return; }  
  93.   
  94. #define REGENTRY_CONV_STORAGETYPE(type, to_sz, from_sz, from_dw, no_result) /  
  95.     CRegEntry& operator=( type Value ) { to_sz return (*this = (LPCTSTR)(buffer)); } /  
  96.     operator type(){ REGENTRY_BINARYTOSTRING return (REGENTRY_SZ_SAFE ? from_sz :(iType == REG_DWORD ? from_dw : no_result)); }  
  97.   
  98. #define REGENTRY_CONV_NUMERIC_STORAGETYPE(type, maxlen, form, from_sz, from_dw) /  
  99.     REGENTRY_CONV_STORAGETYPE(type, _R_BUF(maxlen); _stprintf(buffer, _T(#form), Value);, from_sz, from_dw, 0)  
  100.   
  101.   
  102. /* ==================================== 
  103.  * Include CRegEntry Class Definition 
  104.  * ==================================== */  
  105.   
  106. #include "RegEntry.h"  
  107.   
  108. /* ==================================== 
  109.  * Begin CRegistry Class Definition 
  110.  * ==================================== */  
  111.   
  112. using namespace std;  
  113.   
  114. class CRegistry {  
  115.   
  116. public:  
  117.       
  118.     CRegistry   (DWORD flags = CREG_CREATE);      
  119.     virtual     ~CRegistry() { Close(); for (int i=0; i < _reEntries.size(); ++i) delete _reEntries[i]; delete [] _lpszSubKey; }  
  120.   
  121.     CRegEntry&  operator[](LPCTSTR lpszVName);  
  122.     CRegEntry*  GetAt(size_t n) { assert(n < Count());  return _reEntries.at(n); }  
  123.       
  124.     bool        Open(LPCTSTR lpszRegPath, HKEY hRootKey = HKEY_LOCAL_MACHINE,  
  125.                 DWORD dwAccess = KEY_QUERY_VALUE | KEY_SET_VALUE, bool bAuto = false);  
  126.       
  127.     bool        AutoOpen(DWORD dwAccess);  
  128.     void        AutoClose();  
  129.     void        Close();  
  130.     bool        Refresh();    
  131.   
  132.     static bool KeyExists(LPCTSTR lpszRegPath, HKEY hRootKey = HKEY_LOCAL_MACHINE);  
  133.     bool        SubKeyExists(LPCTSTR lpszSub);    
  134.       
  135.     void        DeleteKey();      
  136.   
  137.     __inline    GetFlags()  {   return __dwFlags; }  
  138.     __inline    Count()     {   return _reEntries.size(); }  
  139.       
  140.     HKEY        hKey;       /* Registry key handle */  
  141.   
  142. protected:  
  143.       
  144.     DWORD       __dwFlags;  
  145.     friend      void CRegEntry::MultiSetAt(size_t nIndex, LPCTSTR lpszVal);  
  146.     friend      void CRegEntry::MultiRemoveAt(size_t nIndex);  
  147.   
  148. private:  
  149.   
  150.     void        InitData();   
  151.     void        DeleteKey(HKEY hPrimaryKey, LPCTSTR lpszSubKey);  
  152.   
  153.     HKEY        _hRootKey;  
  154.     LPTSTR      _lpszSubKey;  
  155.   
  156.     std::vector<CRegEntry *> _reEntries;  
  157. };  
  158.   
  159. #pragma warning(pop)  
  160.   
  161. #endif  

3.Registry.cpp

[cpp] view plaincopy
  1. /*// --- FILE INFORMATION ----------------------------- 
  2.  
  3.   CRegistry.cpp 
  4.   Classes: CRegEntry and CRegistry 
  5.  
  6.   Author:  Stuart Konen 
  7.   Email:   skonen@gmail.com 
  8.  
  9.   Date:    12/1/2004 (MM/DD/YYYY) 
  10.   Version: 1.00 
  11.  
  12.   (-!-) If you're going to use these classes please do not  
  13.   remove these comments... To use these classes, simply #include 
  14.   Registry.h . In MFC you should also turn off precompiled headers 
  15.   for this file, in VC++ this can be done by navigating to: 
  16.  
  17.   Project->Settings->Project Name->CRegistry.cpp->C/C++->Precompiled Headers 
  18.  
  19. *///----------------------------------------------------  
  20. #include "stdafx.h"  
  21. #include "Registry.h"  
  22.   
  23. #ifdef _DEBUG  
  24. #define new DEBUG_NEW  
  25. #undef THIS_FILE  
  26. static char THIS_FILE[] = __FILE__;  
  27. #endif  
  28.   
  29. #pragma warning (disable : 4706)  
  30.   
  31.   
  32. /* =================================================== 
  33.  *  CONSTRUCTOR 
  34.  * =================================================*/  
  35.   
  36. CRegEntry::CRegEntry(CRegistry *Owner) {  
  37.   
  38.     assert(Owner);  
  39.     InitData(Owner);  
  40. }  
  41.   
  42.   
  43.   
  44. /* =================================================== 
  45.  *  CRegEntry::InitData(CRegistry *Owner) 
  46.  * 
  47.  *  Initializes the entries default values and sets the entries 
  48.  *  owner (CRegistry). This is only called during construction. 
  49.  */  
  50.   
  51. void CRegEntry::InitData(CRegistry *Owner) {  
  52.       
  53.     dwDWORD = iType = 0;   
  54.     lpszName = lpszStr = NULL;  
  55.       
  56.     __bStored = false;  
  57.     __bConvertable = true;  
  58.     __cregOwner = Owner;      
  59. }  
  60.   
  61.   
  62.   
  63. /* =================================================== 
  64.  *  CRegEntry::ForceStr() 
  65.  * 
  66.  *  Forces the memory allocation for the entry's string value, if it 
  67.  *  has not already been allocated. 
  68.  */  
  69.   
  70. void CRegEntry::ForceStr() {  
  71.   
  72.     if (lpszStr == NULL) { lpszStr = new _TCHAR[_MAX_REG_VALUE]; lpszStr[0] = 0; }    
  73. }  
  74.   
  75.   
  76. /* =================================================== 
  77.  *  CRegEntry::operator=(LPCTSTR lpszValue) 
  78.  * 
  79.  *  OPERATOR: Assigns a const character array to the open 
  80.  *  registry value. The registry value type will be REG_SZ. 
  81.  */  
  82.   
  83. CRegEntry& CRegEntry::operator=(LPCTSTR lpszValue) {  
  84.   
  85.     size_t  nValueLen = (_tcslen(lpszValue) + 1)*sizeof(TCHAR);  
  86.     assert(nValueLen <= _MAX_REG_VALUE);  
  87.   
  88.     ForceStr(); iType = REG_SZ;   
  89.     _tcsncpy(lpszStr, lpszValue, nValueLen > _MAX_REG_VALUE ? _MAX_REG_VALUE : nValueLen);  
  90.   
  91.     REGENTRY_ALLOWCONV(true)  
  92.     if (REGENTRY_NOTLOADING && REGENTRY_KEYVALID( KEY_SET_VALUE ))  
  93.         RegSetValueEx(__cregOwner->hKey, lpszName, NULL, REG_SZ, (LPBYTE)lpszValue, nValueLen);  
  94.     REGENTRY_TRYCLOSE;  
  95.   
  96.     __bStored = true;  
  97.   
  98.     return *this;  
  99. }  
  100.   
  101.   
  102.   
  103. /* =================================================== 
  104.  *  CRegEntry::operator=(LPDWORD lpdwValue) 
  105.  * 
  106.  *  OPERATOR: Assigns a DWORD to the open registry value. 
  107.  *  The registry value type will be REG_DWORD. 
  108.  */  
  109.   
  110. CRegEntry& CRegEntry::operator=(LPDWORD lpdwValue) {  
  111.       
  112.     iType = REG_DWORD;  
  113.     memcpy(&dwDWORD, lpdwValue, sizeofDWORD ));  
  114.           
  115.     REGENTRY_ALLOWCONV(true)  
  116.     if (REGENTRY_NOTLOADING && REGENTRY_KEYVALID( KEY_SET_VALUE ))  
  117.         RegSetValueEx(__cregOwner->hKey, lpszName, NULL, REG_DWORD, (LPBYTE)&dwDWORD, sizeofDWORD ));  
  118.     REGENTRY_TRYCLOSE;  
  119.   
  120.     __bStored = true;  
  121.       
  122.     return *this;  
  123. }  
  124.   
  125.   
  126.   
  127. /* =================================================== 
  128.  *  CRegEntry::operator=(CRegEntry& cregValue) 
  129.  * 
  130.  *  OPERATOR: Copys value information from the specified 
  131.  *  registry entry (CRegEntry) into this entry. 
  132.  */  
  133.   
  134. CRegEntry& CRegEntry::operator=(CRegEntry& cregValue) {  
  135.   
  136.     if (this == &cregValue)  
  137.         return *this;  
  138.       
  139.     if (lpszName == NULL) {  
  140.         size_t nNameLen = _tcslen(cregValue.lpszName) + 1;  
  141.         lpszName = new _TCHAR[nNameLen]; _tcsncpy(lpszName, cregValue.lpszName, nNameLen);  
  142.     }  
  143.       
  144.     switch ((iType = cregValue.iType)) {  
  145.   
  146.         case REG_SZ:  
  147.             return (*this = (ForceStr(), cregValue.lpszStr));  
  148.             break;  
  149.   
  150.         case REG_MULTI_SZ: {  
  151.             LPTSTR lpszBuf = new _TCHAR[_MAX_REG_VALUE];  
  152.             SetMulti(cregValue.GetMulti(lpszBuf), cregValue.MultiLength());  
  153.             delete [] lpszBuf; return *this;  
  154.             }  
  155.             break;  
  156.         case REG_BINARY: {  
  157.             size_t n = cregValue.vBytes.size(); LPBYTE buf = new BYTE[n];  
  158.             cregValue.GetBinary(buf, n); SetBinary(buf, n);  
  159.             delete [] buf; return *this;  
  160.             }  
  161.             break;  
  162.         default:  
  163.             return (*this = cregValue.dwDWORD);  
  164.     }  
  165. }  
  166.   
  167.   
  168.   
  169. /* =================================================== 
  170.  *  CRegEntry::operator LPTSTR() 
  171.  * 
  172.  *  OPERATOR: Converts (if required) and returns the open registry 
  173.  *  value as a null terminated string. 
  174.  */  
  175.   
  176. CRegEntry::operator LPTSTR() {  
  177.   
  178.     /* If caching is disabled, refresh the entries */  
  179.     REGENTRY_REFRESH_IF_NOCACHE  
  180.   
  181.     assert(__bConvertable); // Check for conversion implementation  
  182.     ForceStr();  
  183.   
  184.     switch (iType) {  
  185.         case REG_DWORD:  
  186.             _stprintf(lpszStr, _T("%lu"), dwDWORD);  
  187.             break;  
  188.         case REG_MULTI_SZ:  
  189.             GetMulti(lpszStr);  
  190.             break;  
  191.         case REG_BINARY: {  
  192.             _tcsncpy(lpszStr, (const _TCHAR*)&vBytes[0], vBytes.size());  
  193.             lpszStr[vBytes.size()] = 0;  
  194.             }  
  195.             break;  
  196.   
  197.     }  
  198.   
  199.     return lpszStr;  
  200. }  
  201.   
  202.   
  203.   
  204. /* =================================================== 
  205.  *  CRegEntry::operator DWORD() 
  206.  * 
  207.  *  OPERATOR: Converts (if required) and returns the open registry 
  208.  *  value as an unsigned 32-bit integer (unsigned long). 
  209.  */  
  210.   
  211. CRegEntry::operator DWORD() {  
  212.   
  213.     /* If caching is disabled, refresh the entries */  
  214.     REGENTRY_REFRESH_IF_NOCACHE  
  215.       
  216.     assert(__bConvertable); // Check for conversion implementation  
  217.   
  218.     REGENTRY_BINARYTOSTRING  
  219.     return (REGENTRY_SZ_SAFE ? _tcstoul(lpszStr, NULL, NULL) : dwDWORD);  
  220. }  
  221.   
  222.   
  223.   
  224. /* =================================================== 
  225.  *  CRegEntry::GetBinary(LPBYTE lpbValue, size_t nLen) 
  226.  * 
  227.  *  Sets the registry value to a binary value (REG_BINARY) 
  228.  * 
  229.  *  Important Params: 
  230.  * 
  231.  *      LPBYTE lpbDest: Pointer to the byte array to store * 
  232.  *      size_t nLen:    Elements contained within the byte array. 
  233.  */  
  234.   
  235. void CRegEntry::SetBinary(LPBYTE lpbValue, size_t nLen) {  
  236.       
  237.     if (!nLen) { assert(nLen); return; }  
  238.       
  239.     iType = REG_BINARY;   
  240.   
  241.     if (REGENTRY_NOTLOADING && REGENTRY_KEYVALID ( KEY_SET_VALUE ) )  
  242.         RegSetValueEx(__cregOwner->hKey, lpszName, NULL, REG_BINARY, lpbValue, nLen);  
  243.     REGENTRY_TRYCLOSE;  
  244.       
  245.     __bStored = true;  
  246.       
  247.     if (vBytes.size() < nLen) vBytes.reserve(nLen);  
  248.     vBytes.clear();  
  249.           
  250.     do { vBytes.push_back(lpbValue[vBytes.size()]); }  
  251.     while (vBytes.size() < nLen);  
  252. }  
  253.   
  254.   
  255.   
  256. /* =================================================== 
  257.  *  CRegEntry::GetBinary(LPBYTE lpbDest, size_t nMaxLen) 
  258.  * 
  259.  *  Gets the binary value of a value stored as REG_BINARY 
  260.  * 
  261.  *  Important Params: 
  262.  * 
  263.  *      LPBYTE lpbDest: Pointer to the byte array to fill 
  264.  *      size_t nMaxLen: The maximum bytes to copy to lpbDest 
  265.  * 
  266.  *  Notes: This will only work for values that were saved 
  267.  *  using the binary registry type specification (REG_BINARY) 
  268.  */  
  269.   
  270. void CRegEntry::GetBinary(LPBYTE lpbDest, size_t nMaxLen) {  
  271.   
  272.     assert(IsBinary()); // Must be stored as Binary  
  273.       
  274.     REGENTRY_REFRESH_IF_NOCACHE  
  275.       
  276.     if ((size_t)(&vBytes.back() - &vBytes.at(0)+1) == vBytes.size()*sizeof(BYTE))  
  277.         memcpy(lpbDest, (LPBYTE)&vBytes.at(0), vBytes.size() > nMaxLen ? nMaxLen : vBytes.size());  
  278.     else  
  279.         for (size_t n=0; n < vBytes.size() && n < nMaxLen; n++)  
  280.             lpbDest[n] = vBytes[n];       
  281. }  
  282.   
  283.   
  284.   
  285. /* =================================================== 
  286.  *  CRegEntry::GetBinaryLength()  
  287.  * 
  288.  *  Returns the size of the binary value in bytes. 
  289.  */  
  290.   
  291. size_t CRegEntry::GetBinaryLength() {  
  292.       
  293.     assert(IsBinary());  
  294.   
  295.     REGENTRY_REFRESH_IF_NOCACHE  
  296.     return vBytes.size();  
  297. }  
  298.   
  299.   
  300.   
  301. /* =================================================== 
  302.  *  CRegEntry::SetMulti(LPCTSTR lpszValue, size_t nLen, bool bInternal) 
  303.  * 
  304.  *  Stores an array of null-terminated string, terminated by two null characters. 
  305.  *  For Example: First String/0Second/Third/0/0 
  306.  * 
  307.  *  Important Params: 
  308.  * 
  309.  *      LPCTSTR lpszValue:  The string consisting of the null-terminated string array 
  310.  *      size_t  nLen:       The number of characters in the string, including null characters 
  311.  * 
  312.  *  Note: For inserting individual null-terminated strings into the array,  
  313.  *  use MultiAdd or MultiSetAt. 
  314.  */  
  315.   
  316. void CRegEntry::SetMulti(LPCTSTR lpszValue, size_t nLen, bool bInternal) {  
  317.   
  318.     size_t nCur = 0, nPrev = 0, nShortLen = nLen;  
  319.   
  320.     /* When this is internal, there is no need to repopulate the vector. */  
  321.     if (bInternal) goto SkipNoInternal;  
  322.   
  323.     iType = REG_MULTI_SZ; vMultiString.clear();   
  324.     if (nLen <= 2) goto SkipNoInternal; // The string is empty : /0/0  
  325.     if (*(lpszValue + nShortLen-1) == '/0')  
  326.         nShortLen--;      
  327.   
  328.     /* Populate a vector with each string part for easy and quick access */  
  329.     while ((nCur = (int)(_tcschr(lpszValue+nPrev, '/0')-lpszValue)) < nShortLen) {         
  330.         vMultiString.push_back(lpszValue+nPrev);  
  331.         nPrev = nCur+1;  
  332.     }  
  333.   
  334.     SkipNoInternal:  
  335.   
  336.     if (REGENTRY_NOTLOADING && REGENTRY_KEYVALID ( KEY_SET_VALUE ) )  
  337.         RegSetValueEx(__cregOwner->hKey, lpszName, NULL, REG_MULTI_SZ, (LPBYTE)lpszValue, nLen*sizeof(TCHAR));  
  338.     REGENTRY_TRYCLOSE;  
  339.   
  340.     __bStored = true;  
  341. }  
  342.   
  343.   
  344.   
  345. /* =================================================== 
  346.  *  CRegEntry::MultiLength(bool bInternal = false) 
  347.  * 
  348.  *  Returns the number of characters (including null) stored  
  349.  *  in the full string. Don't confuse this with MultiCount() 
  350.  *  which returns the number of strings stored in the array. 
  351.  */  
  352.   
  353. size_t CRegEntry::MultiLength(bool bInternal /*false*/) {  
  354.   
  355.     //Ensure correct values with no cache  
  356.     if (!bInternal) REGENTRY_REFRESH_IF_NOCACHE  
  357.   
  358.     for (size_t nLen = 0, nIndex = 0; nIndex < vMultiString.size(); nIndex++)  
  359.         nLen += vMultiString[nIndex].length() + 1;  
  360.   
  361.     return nLen ? nLen+1 : 0;  
  362. }  
  363.   
  364.   
  365.   
  366. /* =================================================== 
  367.  *  CRegEntry::MultiCount() 
  368.  * 
  369.  *  Returns the number of strings located within the array. 
  370.  */  
  371.   
  372. size_t CRegEntry::MultiCount() {  
  373.   
  374.     // Ensure correct values with no cache  
  375.     REGENTRY_REFRESH_IF_NOCACHE  
  376.   
  377.     return vMultiString.size();  
  378. }  
  379.   
  380.   
  381.   
  382. /* =================================================== 
  383.  *  CRegEntry::MultiRemoveAt(size_t nIndex) 
  384.  * 
  385.  *  Simply removes the string stored at the zero-based index of nIndex 
  386.  */  
  387.   
  388. void CRegEntry::MultiRemoveAt(size_t nIndex) {  
  389.   
  390.     // Ensure correct values with no cache  
  391.     REGENTRY_REFRESH_IF_NOCACHE  
  392.   
  393.     assert(nIndex < vMultiString.size());  
  394.     vMultiString.erase(vMultiString.begin()+nIndex);  
  395.   
  396.     // Update the registry  
  397.     REGENTRY_UPDATE_MULTISTRING  
  398.   
  399. }  
  400.   
  401.   
  402.   
  403. /* =================================================== 
  404.  *  CRegEntry::MultiSetAt(size_t nIndex, LPCTSTR lpszVal) 
  405.  * 
  406.  *  Alters the value of a string in the array located at 
  407.  *  the 0 based index of nIndex. The new value is lpszVal. 
  408.  *  The index must be within the bounds of the array, with 
  409.  *  the exception of being == the number of elements in 
  410.  *  which case calling this function is equal to calling 
  411.  *  MultiAdd. 
  412.  */  
  413.   
  414. void CRegEntry::MultiSetAt(size_t nIndex, LPCTSTR lpszVal) {  
  415.   
  416.     // Ensure correct values with no cache  
  417.     REGENTRY_REFRESH_IF_NOCACHE  
  418.   
  419.     assert(nIndex <= vMultiString.size());  
  420.     iType = REG_MULTI_SZ;  
  421.   
  422.     // Add a new string element if == elements+1  
  423.     if (nIndex == vMultiString.size())    
  424.         vMultiString.push_back(lpszVal);  
  425.     else  
  426.         vMultiString[nIndex] = lpszVal;  
  427.       
  428.     // Update the registry  
  429.     REGENTRY_UPDATE_MULTISTRING  
  430. }  
  431.   
  432.   
  433.   
  434. /* =================================================== 
  435.  *  CRegEntry::MultiGetAt(size_t nIndex) 
  436.  * 
  437.  *  Returns a constant pointer to the string located in 
  438.  *  the array at the zero-based index of nIndex. Note that 
  439.  *  the return value is not an STL string. 
  440.  */  
  441.   
  442. LPCTSTR CRegEntry::MultiGetAt(size_t nIndex) {  
  443.   
  444.     // Ensure correct values with no cache  
  445.     REGENTRY_REFRESH_IF_NOCACHE   
  446.   
  447.     assert(nIndex < vMultiString.size() && IsMultiString());  
  448.     return vMultiString[nIndex].c_str();  
  449. }  
  450.   
  451.   
  452.   
  453. /* =================================================== 
  454.  *  CRegEntry::GetMulti(LPCTSTR lpszDest, size_t nMax) 
  455.  * 
  456.  *  Copys the entire null-terminated array string to lpszDest. 
  457.  *  For Example: First String/0Second/Third/0/0 
  458.  * 
  459.  *  Important Params: 
  460.  * 
  461.  *      LPCTSTR lpszDest:   Pointer to the character array to fill. 
  462.  *      size_t  nMax:       The maximum characters to read, including null-characters 
  463.  * 
  464.  *  Note: By default nMax is set to _MAX_REG_VALUE, you can retrieve 
  465.  *  the length of the entire string by calling MultiLength(). 
  466.  */  
  467.   
  468. LPTSTR CRegEntry::GetMulti(LPTSTR lpszDest, size_t nMax) {  
  469.   
  470.     LPCTSTR strBuf;  
  471.     size_t nCur = 0, nLen = 0;  
  472.       
  473.     assert(IsMultiString());  
  474.     if (!IsMultiString()) return &(lpszDest[0] = 0);  
  475.   
  476.     /* If caching is disabled, refresh the entries */  
  477.     REGENTRY_REFRESH_IF_NOCACHE   
  478.       
  479.     for (size_t n=0; n < vMultiString.size() && nCur < nMax; n++) {  
  480.           
  481.         strBuf = vMultiString[n].c_str();   
  482.         nLen = vMultiString[n].length()+1;  
  483.         _tcsncpy(lpszDest + nCur, strBuf, (nLen >= nMax ? (nMax-nCur) : nLen) * sizeof(_TCHAR));  
  484.         nCur += nLen;  
  485.     }  
  486.   
  487.     /* Add the final null termination */  
  488.     *(lpszDest + nCur) = 0;  
  489.       
  490.     return lpszDest;  
  491. }  
  492.   
  493.   
  494. /* =================================================== 
  495.  *  CRegEntry::Delete() 
  496.  * 
  497.  *  Removes the value from the open registry key, returns 
  498.  *  true on success and false on failure. 
  499.  */  
  500.   
  501. bool CRegEntry::Delete() {  
  502.   
  503.     __bStored = false;  
  504.   
  505.     if (REGENTRY_KEYVALID (KEY_SET_VALUE) )  
  506.         return (__cregOwner->AutoClose(), IS_ES(RegDeleteValue(__cregOwner->hKey, lpszName)));  
  507.       
  508.     return false;  
  509. }  
  510.   
  511.   
  512.   
  513. // BEGIN CREGISTRY FUNCTIONS  
  514.    
  515.   
  516. /* =================================================== 
  517.  *  CRegistry CONSTRUCTOR 
  518.  * 
  519.  *  Flags: 
  520.  * 
  521.  *  CREG_CREATE (default) - When attempting to open a key that  
  522.  *  does not exist, create it. 
  523.  * 
  524.  *  CREG_AUTOOPEN - Close the open registry key handle 
  525.  *  after an action has been performed with it. Opens the 
  526.  *  key whenever another action needs to be performed. 
  527.  * 
  528.  * ===================================================*/  
  529.   
  530. CRegistry::CRegistry(DWORD flags) {   
  531.     InitData(); __dwFlags = flags;   
  532. }  
  533.   
  534.   
  535.   
  536. /* =================================================== 
  537.  *  CRegistry::InitData()  
  538.  *  Initializes the variables related to key locations to NULL. 
  539.  */  
  540.   
  541. void CRegistry::InitData() {   
  542.   
  543.     _lpszSubKey = NULL;  
  544.     _hRootKey = hKey = NULL;  
  545. }  
  546.   
  547.   
  548.   
  549. /* =================================================== 
  550.  *  CRegistry::operator []( LPCTSTR lpszVName) 
  551.  * 
  552.  *  OPERATOR: This will return the Registry Entry (CRegEntry) associated 
  553.  *  with the given value name. If the value name does not exist in 
  554.  *  the open key, it will be created. 
  555.  * 
  556.  *  Note: If the value name is created, it is only stored in the actual 
  557.  *  registry when the entry's value has been set. 
  558.  */  
  559.   
  560. CRegEntry& CRegistry::operator []( LPCTSTR lpszVName) {  
  561.       
  562.     size_t nValueNameLen = _tcslen(lpszVName) + 1;  
  563.     assert(nValueNameLen <= _MAX_REG_VALUE);  
  564.   
  565.     for (int i = _reEntries.size()-1; i >=0; i--) {  
  566.         if (!_tcsicmp(lpszVName, _reEntries[i]->lpszName))  
  567.             return *_reEntries[i];  
  568.     }  
  569.       
  570.     /* Entry not found */     
  571.     _reEntries.push_back(new CRegEntry(this));        
  572.     _reEntries.back()->lpszName = new _TCHAR[nValueNameLen];   
  573.     _tcsncpy(_reEntries.back()->lpszName, lpszVName, (nValueNameLen > _MAX_REG_VALUE ? _MAX_REG_VALUE : nValueNameLen));    
  574.   
  575.     return *_reEntries.back();  
  576. }  
  577.   
  578.   
  579.   
  580. /* =================================================== 
  581.  *  CRegistry::KeyExists() 
  582.  * 
  583.  *  Returns true if the key exists and returns false if the key 
  584.  *  does not exist or could not be opened. This may be called 
  585.  *  as a static function. 
  586.  * 
  587.  *  Example:  
  588.  *  CRegistry::KeyExists("Software//Something", HKEY_LOCAL_MACHINE); 
  589.  */  
  590.   
  591. bool CRegistry::KeyExists(LPCTSTR lpszRegPath, HKEY hRootKey) {  
  592.       
  593.     CRegistry cregTemp( NULL );  
  594.     return cregTemp.Open(lpszRegPath, hRootKey, KEY_QUERY_VALUE, true);   
  595. }  
  596.   
  597.   
  598.   
  599. /* =================================================== 
  600.  *  CRegistry::SubKeyExists() 
  601.  * 
  602.  *  Returns true if the subkey exists within the currently 
  603.  *  open key and false if not. 
  604.  */  
  605.   
  606. bool CRegistry::SubKeyExists(LPCTSTR lpszSub) {  
  607.       
  608.     bool bResult;  
  609.     HKEY hTemp;  
  610.   
  611.     if ((__dwFlags & CREG_AUTOOPEN && !AutoOpen(KEY_QUERY_VALUE)) || hKey == NULL) {  
  612.         assert(hKey);  
  613.         return false;  
  614.     }  
  615.   
  616.     bResult = (RegOpenKeyEx(hKey, lpszSub, 0, KEY_QUERY_VALUE, &hTemp) == ERROR_SUCCESS);  
  617.   
  618.     if (bResult) RegCloseKey(hTemp);  
  619.     if (__dwFlags & CREG_AUTOOPEN) AutoClose();  
  620.       
  621.     return bResult;  
  622. }  
  623.   
  624.   
  625.   
  626. /* =================================================== 
  627.  *  CRegistry::Open(LPCTSTR lpszRegPath, HKEY hRootKey, bool bAuto) 
  628.  * 
  629.  *  Opens the key in which values will be read and stored, if the key 
  630.  *  is not already existent in the registry, it will be created (if the 
  631.  *  CREG_CREATE) flag is present while constructing the class. 
  632.  * 
  633.  *  Upon opening the registry key, all of the REG_DWORD and REG_SZ values 
  634.  *  are loaded into a new corresponding CRegEntry for future access. 
  635.  * 
  636.  *  Important Params: 
  637.  * 
  638.  *      LPCTSTR lpszRegPath - A NULL terminated const character array containing, 
  639.  *      the location of the subkey. 
  640.  *      For example: "SOFTWARE//Microsoft//Windows//CurrentVersion//Run" 
  641.  * 
  642.  *      HKEY hRootKey - An open key handle to the root key. By default 
  643.  *      this value is set as HKEY_LOCAL_MACHINE. 
  644.  *      Another Example: HKEY_CURRENT_USER 
  645.  * 
  646.  *  Returns true on success and false on failure. 
  647.  */  
  648.   
  649.   
  650. bool CRegistry::Open(LPCTSTR lpszRegPath, HKEY hRootKey, DWORD dwAccess, bool bAuto) {  
  651.   
  652.     bool bNew = true;  
  653.   
  654.   
  655.     /* If the key is being auto opened, skip directly to opening */  
  656.     if (bAuto) goto SkipNoAuto;   
  657.   
  658.     /* The key is being opened manually, if the key location differs 
  659.     from the last opened location, clear the current entries and 
  660.     store the path information for future auto opening and key 
  661.     deletion using DeleteKey() */     
  662.   
  663.     if (_lpszSubKey){  
  664.   
  665.         if (_tcsicmp(lpszRegPath, _lpszSubKey)) {                 
  666.               
  667.             /* If new key, clear any currently stored entries */  
  668.             for (size_t n=0; n<_reEntries.size(); n++)  
  669.                 delete _reEntries[n];  
  670.   
  671.             _reEntries.clear();  
  672.             delete [] _lpszSubKey;  
  673.   
  674.         } else bNew = false;  
  675.     }  
  676.   
  677.     if (bNew) {  
  678.       
  679.         /* Store path information for auto opening */  
  680.         _lpszSubKey = new _TCHAR[_tcslen(lpszRegPath)+1];  
  681.         _tcscpy(_lpszSubKey, lpszRegPath);  
  682.     }  
  683.       
  684.     _hRootKey = hRootKey;  
  685.       
  686.       
  687.     SkipNoAuto:  
  688.       
  689.     /* This is where the key is actually opened (if all goes well). 
  690.     If the key does not exist and the CREG_CREATE flag is present, 
  691.     it will be created... Any currently opened key will be closed 
  692.     before opening another one. After opening the key, Refresh() is 
  693.     called and the key's values are stored in memory for future use. */  
  694.       
  695.     if (hKey != NULL) Close();  
  696.   
  697.   
  698.     /* If auto opening is set and this is a manual opening 
  699.     set the appropriate access rights */  
  700.   
  701.     if (__dwFlags & CREG_AUTOOPEN && !bAuto) {  
  702.         dwAccess = CREG_CREATE ? KEY_CREATE_SUB_KEY | KEY_QUERY_VALUE : KEY_QUERY_VALUE;  
  703.     }  
  704.   
  705.   
  706.     /* When key creation is enabled and auto opening is disabled, 
  707.     include key creation in the access rights */  
  708.   
  709.     else if (__dwFlags & ~CREG_AUTOOPEN && __dwFlags & CREG_CREATE)  
  710.         dwAccess |= KEY_CREATE_SUB_KEY;  
  711.   
  712.   
  713.       
  714.     /* Open or create the sub key, and return the result: */  
  715.     LONG lResult = (__dwFlags & CREG_CREATE ?  
  716.         RegCreateKeyEx(hRootKey, lpszRegPath, 0, NULL, REG_OPTION_NON_VOLATILE, dwAccess, NULL, &hKey, NULL)  
  717.     : RegOpenKeyEx(hRootKey, lpszRegPath, 0, dwAccess, &hKey));  
  718.       
  719.     return (lResult == ERROR_SUCCESS ? (bAuto ? true : Refresh()) : false);  
  720. }  
  721.   
  722.   
  723.   
  724. /* =================================================== 
  725.  *  CRegistry::AutoOpen() 
  726.  *   
  727.  *  If the CREG_AUTOOPEN flag is true, this function is called whenever 
  728.  *  an action needs to be performed involving the registry key. 
  729.  * 
  730.  *  DWORD dwAccess controls the access required for key use. 
  731.  */  
  732.   
  733. bool CRegistry::AutoOpen(DWORD dwAccess) {  
  734.   
  735.     assert(_lpszSubKey != NULL);      
  736.     return (hKey == NULL && __dwFlags & CREG_AUTOOPEN ? Open(_lpszSubKey, _hRootKey, dwAccess, true) : true);  
  737. }  
  738.   
  739.   
  740.   
  741. /* =================================================== 
  742.  *  CRegistry::AutoClose() 
  743.  *   
  744.  *  If the CREG_AUTOOPEN flag is true, this function is called whenever 
  745.  *  an action has been performed on an open registry key and the key is no longer 
  746.  *  being accessed. 
  747.  */  
  748.   
  749. void CRegistry::AutoClose() {  
  750.   
  751.     if (__dwFlags & CREG_AUTOOPEN) Close();  
  752. }  
  753.   
  754.   
  755.   
  756. /* =================================================== 
  757.  *  CRegistry::Refresh() 
  758.  *   
  759.  *  Enumerates all the REG_SZ, REG_BINARY and REG_DWORD values within the open 
  760.  *  registry key and stores them in a CRegEntry class for future 
  761.  *  access. Returns true on success and false on failure. 
  762.  */  
  763.   
  764. bool CRegistry::Refresh() {  
  765.   
  766.     DWORD   dwBufferSize;  
  767.     DWORD   dwType;  
  768.     DWORD   dwNameLen;  
  769.     DWORD   dwValueCount;  
  770.     LPBYTE  lpbBuffer;  
  771.   
  772.     DWORD   dwPrevFlags = __dwFlags;  
  773.     _TCHAR  cValueName[_MAX_PATH];    
  774.   
  775.       
  776.     if ((__dwFlags & CREG_AUTOOPEN && !AutoOpen(KEY_QUERY_VALUE)) || hKey == NULL)  
  777.         return false;  
  778.   
  779.     if (NOT_ES(RegQueryInfoKey(hKey, NULL, NULL, NULL, NULL, NULL, NULL, &dwValueCount, NULL, NULL, NULL, NULL)))  
  780.         return false;  
  781.   
  782.     lpbBuffer = new BYTE[_MAX_REG_VALUE];  
  783.   
  784.   
  785.     /* Halt auto opening and set loading flag */      
  786.     __dwFlags = (__dwFlags | CREG_LOADING) & ~CREG_AUTOOPEN;  
  787.       
  788.   
  789.     if (dwValueCount > _reEntries.size())  
  790.         _reEntries.reserve(dwValueCount);  
  791.   
  792.     forDWORD dwIndex = 0; dwIndex < dwValueCount; dwIndex++) {  
  793.   
  794.         dwNameLen = sizeof(cValueName); dwBufferSize = _MAX_REG_VALUE;    
  795.         cValueName[0] = 0;  
  796.           
  797.         if (NOT_ES(RegEnumValue(hKey, dwIndex, cValueName, &dwNameLen, NULL, &dwType, lpbBuffer, &dwBufferSize)))  
  798.             continue;  
  799.   
  800.         switch (dwType) {  
  801.                           
  802.             case REG_DWORD:                                               
  803.                 this[0][cValueName] = (LPDWORD)lpbBuffer;                 
  804.                 break;  
  805.                   
  806.             case REG_SZ:  
  807.                 this[0][cValueName] = (LPCTSTR)lpbBuffer;  
  808.                 break;                
  809.   
  810.             case REG_MULTI_SZ:  
  811.                 this[0][cValueName].SetMulti((LPCTSTR)lpbBuffer, dwBufferSize/sizeof(TCHAR));                 
  812.                 break;    
  813.   
  814.             case REG_BINARY:  
  815.                 this[0][cValueName].SetBinary(lpbBuffer, (size_t)dwBufferSize);  
  816.                 break;                
  817.         }  
  818.     }  
  819.   
  820.     if ((__dwFlags = dwPrevFlags) & CREG_AUTOOPEN) AutoClose();  
  821.     delete [] lpbBuffer;  
  822.   
  823.     return true;  
  824. }  
  825.   
  826.   
  827.   
  828. /* =================================================== 
  829.  *  CRegistry::DeleteKey() 
  830.  *   
  831.  *  Deletes the key which is currently opened, including any 
  832.  *  subkeys and values it may contain. 
  833.  * 
  834.  *  NOTE: Use extreme caution when calling this function 
  835.  */  
  836.   
  837. void CRegistry::DeleteKey() {  
  838.   
  839.     OSVERSIONINFO osvi;  
  840.     osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);  
  841.       
  842.     if (GetVersionEx(&osvi) && osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)  
  843.         DeleteKey(_hRootKey, _lpszSubKey);  
  844.     else   
  845.         RegDeleteKey(_hRootKey, _lpszSubKey);  
  846.   
  847.     Close();  
  848. }  
  849.   
  850.   
  851.   
  852. /* =================================================== 
  853.  *  CRegistry::DeleteKey(HKEY hPrimaryKey, LPCTSTR lpszSubKey) 
  854.  *   
  855.  *  Private member function which is called by DeleteKey() 
  856.  *  This function is designed for NT based systems as it recursively 
  857.  *  deletes any subkeys present. 
  858.  */  
  859.   
  860. void CRegistry::DeleteKey(HKEY hPrimaryKey, LPCTSTR lpszSubKey) {  
  861.   
  862.     DWORD dwKeyLen;  
  863.     FILETIME ftTemp;  
  864.     HKEY hTempKey;  
  865.   
  866.     LONG   lResult = ERROR_SUCCESS;  
  867.     LPTSTR lpszKey = new _TCHAR[_MAX_PATH];   
  868.   
  869.     if (!_tcslen(lpszSubKey) || !hPrimaryKey) { assert(hPrimaryKey != NULL); goto cleanup; }  
  870.   
  871.     if (IS_ES(RegOpenKeyEx(hPrimaryKey, lpszSubKey, 0, KEY_ENUMERATE_SUB_KEYS | KEY_WRITE, &hTempKey))){  
  872.           
  873.         while (IS_ES(lResult)) {  
  874.               
  875.             dwKeyLen = _MAX_PATH;  
  876.             lResult  = RegEnumKeyEx(hTempKey, 0, lpszKey, &dwKeyLen, NULL, NULL, NULL, &ftTemp);  
  877.   
  878.             if (lResult == ERROR_SUCCESS) DeleteKey(hTempKey, lpszKey);  
  879.             else if (lResult == ERROR_NO_MORE_ITEMS) RegDeleteKey(hPrimaryKey, lpszSubKey);  
  880.         }  
  881.         RegCloseKey(hTempKey); hTempKey = NULL;  
  882.     }  
  883.   
  884.     cleanup: delete [] lpszKey;            
  885. }  
  886.   
  887.   
  888.   
  889. /* =================================================== 
  890.  *  CRegistry::Close() 
  891.  * 
  892.  *  If a key is currently open, it will be closed. This should 
  893.  *  be called when you no longer need to access the registry key 
  894.  *  and the CREG_AUTOOPEN flag is not true. However, Close() is  
  895.  *  called on class deconstruction so it is not required. 
  896.  */  
  897.   
  898. void CRegistry::Close() {  
  899.   
  900.     if (hKey != NULL) {   
  901.         RegCloseKey(hKey); hKey = NULL;   
  902.     }  
  903. }  

 

   (二)具体实施方案

1.把以上的三个文件加入到你的工程中去;

2.在MainFrm.cpp中包含相关的头文件

#include "Registry.h"
#include "RegEntry.h"

3.在MainFrm的析构函数中执行注册表的信息清理工作:

    首先,获取本程序自定义的文档类型。我在网上没找着相应的解决方案,于是自己根据mfc的api自己编了一个,希望大家不要见笑,更希望大家能够提供更好的解决方案。

POSITION doc_position;
 doc_position = AfxGetApp()->GetFirstDocTemplatePosition();
 CString type;
 AfxGetApp()->GetNextDocTemplate(doc_position)->GetDocString(type,CDocTemplate::filterExt);

      然后,使用上述的封装类类删除由EnableShellOpen();RegisterShellFileTypes(TRUE);自动生成的注册表信息。主要有两项:一个以自定义的文档类型名称来命名的节点,另一个是以前一个节点的具体值来命名的节点。具体代码如下:

CRegistry reg(0 & ~CREG_CREATE),reg2(0 & ~CREG_CREATE);
 CString info;
 if(reg.Open(type,HKEY_CLASSES_ROOT)){
  if (reg.GetAt(0)->Exists()){   
   if(reg.GetAt(0)->IsString())
    info.Format("%s",reg.GetAt(0)->operator LPTSTR());
  }
  if(reg2.Open(info,HKEY_CLASSES_ROOT)){
   reg2.DeleteKey();
   reg.DeleteKey();
  }
 }