Click here to Skip to main content
Click here to Skip to main content

A Registry Class

By , 6 Aug 2001
 

Overview

I created this class to make it easy to work with the Registry. For this I created the CRegistry class.

The CRegistry Class

The CRegistry class has a set of functions that make using the registry easy.

CRegistry::OpenKey

The OpenKey opens the specified registry key.

BOOL OpenKey(enum Keys hKey, LPCTSTR szKey);

Parameters

enum Keys hKey - Handle to any of the following predefined values:

CRegistry::classesRoot

CRegistry::currentUser

CRegistry::localMachine

CRegistry::currentConfig

CRegistry::users

Windows NT/2000: CRegistry::performanceData

Windows 95/98: CRegistry::dynData

LPCTSTR szKey - Pointer to a null-terminated string containing the name of the key to open.

If the function succeeds, this returns TRUE.

See sample

<a name="Sample1">
  CRegistry pReg;
  
  pReg.OpenKey(CRegistry::currentUser, "Entry1\\carlos1");
  CString str = _T("");

  if(pReg.GetValue("SZVAL1", str))
    AfxMessageBox("The Value SZVAL1 don't exists", MB_ICONWARNING);
    
  DWORD dwVal = 0;
  pReg.GetValue("DWVAL", dwVal);

  pReg.GetValue(NULL, str);
  pReg.CloseKey();</a>

CRegistry::CreateKey

The CreateKey function creates the specified registry key. If the key already exists in the registry, the function opens it.

BOOL CreateKey(enum Keys hKey, LPCTSTR szKey);

Parameters

enum Keys hKey - Handle to any of the following predefined values:

CRegistry::classesRoot

CRegistry::currentUser

CRegistry::localMachine

CRegistry::currentConfig

CRegistry::users

Windows NT/2000: CRegistry::performanceData

Windows 95/98: CRegistry::dynData

LPCTSTR szKey - Pointer to a null-terminated string containing the name of the key to open or create.

If the function succeeds, this returns TRUE.

CRegistry::DeleteKey

The DeleteKey function deletes a subkey.

BOOL DeleteKey(enum Keys hKey, LPCTSTR szKey);

Parameters

enum Keys hKey - Handle to any of the following predefined values:

CRegistry::classesRoot

CRegistry::currentUser

CRegistry::localMachine

CRegistry::currentConfig

CRegistry::users

Windows NT/2000: CRegistry::performanceData

Windows 95/98: CRegistry::dynData

LPCTSTR szKey - Pointer to a null-terminated string containing the name of the key to delete.

If the function succeeds, this returns TRUE.

CRegistry::GetValue

The GetValue function retrieves the data for a specified value name from the open registry key.

BOOL GetValue(LPCTSTR lpValueName, CString& strValue);
BOOL GetValue(LPCTSTR lpValueName, DWORD& dwValue);

Parameters

LPCTSTR lpValueName - Pointer to a null-terminated string containing the name of the value to get

CString& strValue - Pointer to a buffer that receives the value's data

DWORD& dwValue - Pointer to a buffer that receives the value's data

If the function succeeds, this returns TRUE.

See sample

CRegistry::SetValue

The SetValue function sets the data and type of a specified value under a registry key.

BOOL SetValue(LPCTSTR lpValueName, LPCTSTR lpData);
BOOL SetValue(LPCTSTR lpValueName, DWORD dwValue);

Parameters

LPCTSTR lpValueName - Pointer to a null-terminated string containing the name of the value to set

CString& strValue - Pointer to a buffer containing the data to be stored with the specified value name

DWORD& dwValue - Pointer to a buffer containing the data to be stored with the specified value name

If the function succeeds, this returns TRUE.

See sample

<a name="Sample2">pReg.OpenKey(CRegistry::currentUser, "Entry1\\carlos1");

pReg.SetValue("SZVAL", "STRVAL");
pReg.SetValue(NULL, "default");
pReg.SetValue("DWVAL", 34); 

pReg.CloseKey();</a>

CRegistry::DeleteValue

The DeleteValue function removes a named value from the specified registry key

BOOL DeleteValue(LPCTSTR lpValueName);

Parameters

LPCTSTR lpValueName - Pointer to a null-terminated string that names the value to remove.

If the function succeeds, this returns TRUE.

See sample

<a name="Sample3">  CRegistry pReg;

  pReg.OpenKey(CRegistry::currentUser, "Entry1\\carlos1");

  pReg.DeleteValue("SZVAL");	
  pReg.CloseKey();</a>

CRegistry::CloseKey

The CloseKey function closes the registry key.

void CloseKey();

See sample

Updates

04 August 2001: Version 1.0 Released.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Carlos Antollini
Architect Citigroup
Argentina Argentina
Member
Carlos Antollini is a software engineer working on Object Oriented, Visual C++, MFC, COM, ATL, ADO, Internet technologies and Business Intelligence.
Carlos is originally from Argentina, he was living for several years in Fort Lauderdale, Florida, working for Citibank. Then he started his own business.
Carlos is the creator of piFive[^], a family of BI Analytic Platform software, that it deals next to, latinsys[^], his partner in businesses...
Currently he is sharing his passion for project management and BI at Citigroup.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralRe: Almost perfect!memberCarlos Antollini15 May '04 - 15:42 
Thanks...Blush | :O
 
Regards
 
Carlos Antollini
Do you know piFive[^] ?

Questionbug with 2000pro ?memberalex-pcom22 Jan '04 - 2:17 
Hello
this code works well on WindowsXP
but does nothing on 2000 pro D'Oh! | :doh: :

CString value;
value.Format("%s", buff);
CRegistry regs;

if (regs.CreateKey(CRegistry::currentUser, "Software\\xxx")==FALSE)
AfxMessageBox("Error CreateKey");
 
if (regs.CreateKey(CRegistry::currentUser, "Software\\xxx\\yyy")==FALSE)
AfxMessageBox("Error CreateKey2");
if (regs.OpenKey(CRegistry::currentUser, "Software\\xxx\\yyy")==FALSE)
AfxMessageBox("Error OpenKey");
if (regs.SetValue( "IDVAL", (LPCTSTR) value )==FALSE)
AfxMessageBox("Erreur SetValue");

regs.CloseKey();

 
I have no xxx or yyy keys in registry even after rebooting the system
 
Am I doing something wrong ?

AnswerRe: bug with 2000pro ?memberCarlos Antollini22 Jan '04 - 3:36 
You are not doing something wrong.
I tested your code, And I din't find any problem.
It,s very strange because I wrote that class over windows 2000 Pro, and Now I'm using a Windows 2000 Advance Server and XP Pro and I didn't find any strange behavior.
Check if you have any permits problem over the registry, or something like that....
 
Best Regards
 
Carlos Antollini
Do you know piFive[^] ?

GeneralRe: bug with 2000pro ?memberShikamaru27 Apr '04 - 21:03 
I've got the same prob.Neway,how do i check my registry permit?? Thanx in advance.
 
3.142
GeneralSource updated for VS7memberralfoide30 Sep '03 - 11:42 
Hi!
 
I updated the source for use with VS7/.Net and saved an archive here:
http://www.beatware.com/~ralf/CRegistry_VS7_RM20030930.zip
 
Modifications:
- Unicode and MBCS (using LPTSTR and TCHAR)
- GetValue string using a allocated buffer of the right size freed after
- No more warning or errors with VS7
 
I'll probably remove the RegFlushKey too later, btw.
 
Enjoy
R/
QuestionShould RegFlushKey be used?memberBaz18 Jul '03 - 4:53 
Hi there Carlos! Great job on the creation of another great MFC/C++ class! Wink | ;)
 
Anyway, should you be using the RegFlushKey() function as the MSDN states:
 
"An application should only call RegFlushKey if it requires absolute certainty that registry changes are on disk. In general, RegFlushKey rarely, if ever, need be used."
 
because.... (it says earlier in the article)...
 
"It is not necessary to call RegFlushKey to change a key. Registry changes are flushed to disk by the registry using its lazy flusher"
 
I tend to stick to what Microsods say cos if they mention something, I tend to think of it as an admittance of a bug (me being cynical?!Unsure | :~ )What's your ideas on that?
GeneralVC7 compiler errors/warningsmemberC++ Hacker23 Jan '03 - 3:17 
Hello,
I get the following errors compiling with VC7:
 
Compiling...
Registry.cpp
e:\temp\BugRTCsu\Registry.h(28) : error C2058: constant expression is not integral
e:\temp\BugRTCsu\Registry.h(29) : error C2058: constant expression is not integral
e:\temp\BugRTCsu\Registry.h(30) : error C2058: constant expression is not integral
e:\temp\BugRTCsu\Registry.h(31) : error C2058: constant expression is not integral
e:\temp\BugRTCsu\Registry.h(32) : error C2058: constant expression is not integral
e:\temp\BugRTCsu\Registry.h(33) : error C2058: constant expression is not integral
e:\temp\BugRTCsu\Registry.h(35) : error C2058: constant expression is not integral
 
If I cast the keys to (int) I get the following warnings
 
Registry.h(28) : warning C4311: 'type cast' : pointer truncation from 'HKEY' to 'int'
Registry.h(29) : warning C4311: 'type cast' : pointer truncation from 'HKEY' to 'int'
Registry.h(30) : warning C4311: 'type cast' : pointer truncation from 'HKEY' to 'int'
Registry.h(31) : warning C4311: 'type cast' : pointer truncation from 'HKEY' to 'int'
Registry.h(32) : warning C4311: 'type cast' : pointer truncation from 'HKEY' to 'int'
Registry.h(33) : warning C4311: 'type cast' : pointer truncation from 'HKEY' to 'int'
Registry.h(35) : warning C4311: 'type cast' : pointer truncation from 'HKEY' to 'int'
 
You can resolve this problem by deleting the enum Keys and changing all parameters of the
member functions from enum Keys to HKEY.
 
warnings (switch /Wp64 set):
Registry.cpp(47) : warning C4267: 'argument' : conversion from 'size_t' to 'DWORD', possible loss of data
Registry.cpp(113) : warning C4311: 'type cast' : pointer truncation from 'DWORD *__w64 ' to 'DWORD'
 
Can you please resolve this problem, thanks a lot,
 
Andreas.

GeneralEnumKeymemberMichael Ehehalt8 Dec '02 - 19:41 
What do you mean about new functionality EnumKey?
 
Code of function EnumKey:
 
BOOL EnumKey(DWORD index, LPTSTR lpKey)
{
 
BOOL bRet = FALSE;
DWORD lenKey;
LPSTR lpstrValue;
 
lpstrValue = (LPSTR)malloc(sizeof(char) * 256);
memset(lpstrValue, 0, sizeof(char) * 256);
 
if(::RegEnumKeyEx((HKEY)m_hKey, index, lpstrValue, &lenKey, 0, NULL, NULL, NULL) == ERROR_SUCCESS)
{
strcpy(lpKey, lpstrValue);
bRet = TRUE;
}
else
{
strcpy(lpKey, "");
}
 
return bRet;
 
}

 
The Keys can get in a loop like this:
 

DWORD index = 0;
LPTSTR lpKey=new char[256];
 
while(EnumKey(index, lpKey))
{
...
 
index++;
}

 
Bye
 

GeneralRe: EnumKeymemberBruno Scopinho4 Jan '07 - 12:31 
Very nice code Michael Ehehalt.
 
Thanks! Smile | :)
Generalbug in GetValuememberMichael Ehehalt8 Dec '02 - 19:31 
In GetValue the lpcbData (msdn: Pointer to a variable that specifies the size, in bytes) is set to 1024, but the length of the read string is only 256 - both hardcoded! So if the string in the registry is bigger than 256 the program crashes ... Smile | :)
 

Generalbug in the readstringmemberThomas George1 Oct '02 - 14:08 
You can get the length of the string and allocate space rather than hardcoding a 256 byte buffer.

GeneralProblem with Hkey local machinesussZvika Vered18 Aug '02 - 6:11 
:(The class returns FALSE if the user is not administrator
and tries to open a key and get values in HKEY_LOCAL_MACHINE.
The key is in: \software\ELTA\MyApp
 

GeneralRe: Problem with Hkey local machinememberRaimon814 Nov '05 - 2:34 
Even I have a administrator rigts, that I can't remove some keys from HKEY_LOCAL_MACHINE. When I try that with regedit application, befor I am able to remove a key I must change a permission to them (right mouse click on key and permissions). After I set all permission to my group I am able to remove register entries.
 
My question is how can I change permission to the key from Windows API? That is needed if I want to remove keys from HKEY_LOCAL_MACHINE.
 
Janusz
GeneralProblem with .Net!memberGeorge Clarence6 Aug '02 - 23:12 
Hi!
I have used your very usefull class within my Project in VC++ 6.0 and it has worked properly. Now, I have upgraded to .Net and I have recompiled my Project, but I have recieved several errors, like this one:
error C2058: constant expression is not integral
The errors are with these lines:
classesRoot = HKEY_CLASSES_ROOT,
classesRoot = HKEY_CLASSES_ROOT,
currentUser = HKEY_CURRENT_USER,
localMachine = HKEY_LOCAL_MACHINE,
currentConfig = HKEY_CURRENT_CONFIG,
users = HKEY_USERS,
performanceData = HKEY_PERFORMANCE_DATA,
etc...
 
Can you help me please?
 
Best regards
-George ClarenceRose | [Rose] Roll eyes | :rolleyes: Big Grin | :-D

GeneralRe: Problem with .Net!memberCarlos Antollini7 Aug '02 - 3:47 
George, I have not the .Net in my Office, but when I stay at home I will test my class, and will make the necesary changes, for the class works in .Net....
 
Cheers!!!
 
Carlos Antollini.
Sonork ID 100.10529 cantollini
GeneralRe: Problem with .Net!memberGeorge Clarence7 Aug '02 - 4:32 
Dear Carlos,
thank you very much for your message. I have resolved this problem by adding (int) in front of the key names.
 
I still have other problems with my project. The warning level is 3, is it too high? Why I recieve so many strange errors?
 
Best regards
GeorgeCry | :((
GeneralRename keysussZhangFei3 Aug '02 - 6:19 
anyone know how to rename a key programmatically? I cann't a function call to rename registry key name.
 
Thanks
GeneralSub-key deletesussAnonymous16 Jul '02 - 22:36 
Great class. Very minor suggestion is that you can use the DeleteKey to delete a key and all its sub-keys on Win9x, but it doesnt work the same on WinNT/2000. If you replace the RegDeleteKey with SHDeleteKey then it works the same on all systems! (you'll need IE 4, and link with shlwapi.dll)
GeneralC1010 ErrormemberMatt Newman24 Nov '01 - 8:34 
I keep getting this error (unexpected end of file while looking for a precompiled header). How do I fix this?
 

-Matt Newman
-Matt Newman


GeneralRe: C1010 ErrormemberCarlos Antollini26 Nov '01 - 3:52 
You need to use automatic precompiled headers.
 
If you don't Know how set this propierty notify me, That I will explain...
 

Best Regards
 
Carlos Antollini.
Sonork ID 100.10529 cantollini
GeneralRe: C1010 ErrormemberMatt Newman26 Nov '01 - 7:56 
I just created a new CRegistry class and copied the functions, copyright etc. I have also converted it to support UNICODE. If you want I can clean it up and send you the changes.
 

-Matt Newman
-Matt Newman


GeneralRe: C1010 ErrormemberCarlos Antollini26 Nov '01 - 8:53 
Yes, I hope to send me your version...Smile | :)
 
Best Regards!!!

 
Carlos Antollini.
Sonork ID 100.10529 cantollini
GeneralRe: C1010 ErrormemberMatt Newman26 Nov '01 - 15:42 
I'll send it as soon as I get my computer working. I am waiting for parts that were supposed to get here a couple days ago and my CD-burner decided not to work with XP so I can't even backup and reinstall.
 

-Matt Newman
-Matt Newman


GeneralRe: C1010 ErrormemberMatt Newman13 Dec '01 - 10:57 
I got my computer working and as soon as I get back to productivity I will let you know when the UNICODE version is ready.
 

-Matt Newman
-Matt Newman

-Sonork ID: 100.11179:BestSnowman
GeneralRe: C1010 Errormemberbaur zeng30 Oct '02 - 14:38 
I also need the UNIcode version of registry class.I wonder if you could possibly forward me a copy. I will really appreciate for it.
My email box is:baur@sjtu.edu.cn.
 
Thank you very much.Blush | :O

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 7 Aug 2001
Article Copyright 2001 by Carlos Antollini
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid