65.9K
CodeProject 正在变化。 阅读更多。
Home

另一个注册表类

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.92/5 (36投票s)

2002年7月1日

CPOL

2分钟阅读

viewsIcon

196620

downloadIcon

2581

一个具有重载运算符的注册表类,可以将注册表值用作普通变量。

引言

在许多项目中,我需要存储简单的字符串、DWORDS 或窗口位置的 CRect 到注册表中。我知道市面上有很多注册表类,为什么还要再写一个呢?

答案:简单性。我希望像给变量赋值一样简单地写入注册表。就像神经控制器中的eeprom变量一样(那些使用这些控制器的人都知道我的意思)。所以我编写了这样一个类。

用法

那么,如何使用这个类——或者说这些类。我为 CStringDWORDCRectCPoint 编写了单独的类。

// initialize the variables
CRegString mystring("Software\\Company\\Subkey\\MyString", "defaultvalue");
CRegRect   myrect("Software\\Company\\Subkey\\MyRect", CRect(1,1,1,1));
CRegDWORD  myword("Software\\Company\\Subkey\\mydword", 100, 
                     TRUE, HKEY_LOCAL_MACHINE);
CRegPoint  mypoint("Software\\Company\\Subkey\\mypoint");

// now use those variables
CString str = mystring;     //if registry does not exist, the default value is used
mystring = "TestValue";     //"TestValue" is stored in the registry
mystring += "!";            //now the registry value MyString contains "TestValue!"
myrect = CRect(100,200,300,400);    //store in the registry
LPRECT lpR = (LPRECT)myrect;
myword = GetTickCounts();   //just an example
mypoint = CPoint(0,0);

如你所见,一旦 CRegXXX 对象知道它被分配到哪个注册表键/值,你就可以像使用任何其他变量一样使用它!

为了避免对注册表进行过多的访问,该值会被缓存。写入仅当新值与当前值不同时才会发生。读取仅在构造函数中发生一次。由于这种缓存行为可能会导致一些问题,你可以使用 read()write() 方法强制读取和写入注册表。要禁用缓存并强制类始终访问注册表,只需在构造函数中设置即可。CRegDWORD 的构造函数如下所示

/**
* Constructor.
* @param key the path to the key, including the key. 
*            example: "Software\\Company\\SubKey\\MyValue"
* @param def the default value used when the key does not exist or 
*            a read error occured
* @param force set to TRUE if no cache should be used, i.e. always read and write 
*              directly from/to registry
* @param base a predefined base key like HKEY_LOCAL_MACHINE. see the SDK 
*             documentation for more information.
*/
CRegDWORD(CString key, DWORD def = 0, BOOL force = FALSE, 
          HKEY base = HKEY_CURRENT_USER);

CRegStringCRegRectCRegPoint 具有类似的构造函数。有关详细信息,请参阅头文件。

并非“基”类的所有方法都被重载。因此,如果你想使用 CString 类的一些方法,你必须先将 CRegString 转换为 CString

int l = ((CString)mystring).GetLength();
((CString)mystring).Trim();

请注意,在第二行使用 Trim() 的地方,更改后的字符串不会写入注册表!

请记住:把关于“又一个注册表类”之类的抱怨留给自己吧。如果你不喜欢它,就不要使用它!

更新

  • 2003年4月2日
    1. 添加了用于不使用 MFC 的类:CRegStdString、CRegStdDWORD
    2. 现在也支持 UNICODE 编译
  • 2002年7月9日
    1. 更正了 Hans Dietrich 发现的一个错误
    2. 扩展了类,添加了两个方法:removeKey() 和 removeValue()

Daniel Andersson 编写了这个类的模板化版本。请参阅他的文章 这里

© . All rights reserved.