A Class For Handling The Registry

Changes in Revision 2
Changes in Revision 3
Changes in Revision 4
Changes in Revision 5
Usage
Download

Often one can read in the newsgroups, that someone is looking for an MFC class that encapsulates the registry. In fact, MFC does not provide such a class. As long as one has no need to work with the registry in another location than HKEY_CURRENT_USER\Software\[<company>\]<product>, one can use CWinApp::GetProfile*() and CWinApp::WriteProfile*().

If one wants to use the registry more flexible, then one has to use the API-functions with their dozens of parameters. I don't know why MS doesn't provide a registry class in MFC - that would be quite easy ...

The CRegistry class I've developed allows one to use the registry in a simple way. In addition to the basic operations (loading and storing data), the class provides some more features. For instance one can walk the registry tree and perform some operations on any key/value-hit. Furthermore the class encapsulates differences between NT and Win95 (Aeh - you guessed that the Win32 API should be identical on both systems? Yes - the API is identical, but the performed action is not! Take a closer look at the description of the RegDeleteKey() function for instance.)

To handle all the different data types one can put into the registry, the CRegistry class uses an information holder class CRegVal. If you have to load a string from
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\WinLogon\DefaultUserName
you can do it as follows:

CString strKey = TEXT("Software\\Microsoft\\Windows NT\\CurrentVersion\\WinLogon");
CRegistry reg(HKEY_LOCAL_MACHINE);  // otherwise it defaults to HKEY_CURRENT_USER
CString strDefaultUserName;
CRegVal regval;
if( reg.LoadKey(strKey, TEXT("DefaultUserName"), regval) )
        if( regval.GetValue(strDefaultUserName) )
                // yep - got the name
Simple datatypes (numbers and strings) will be supported directly by the CRegistry class, so you can write the sample above as follows:
CString strKey = TEXT("Software\\Microsoft\\Windows NT\\CurrentVersion\\WinLogon");
CRegistry reg(HKEY_LOCAL_MACHINE);  // otherwise it defaults to HKEY_CURRENT_USER
CString strDefaultUserName;
if( reg.LoadKey(strKey, TEXT("DefaultUserName"), strDefaultUserName) )
        // yep - got the name
... but, if CRegistry::LoadKey() returns FALSE, this makes it harder to check whether the type of the registry key is wrong or the entry does not exist.

CRegistry doesn't support security (but that was no handicap for me so far :-)
 

Changes in Revision 2

You can use Registry.cpp if you want to use the registry classes in a non-MFC application and RegMFC.cpp in an MFC-based application. RegMFC.cpp will support some more methods for use with MFC.
For a build with MFC, you have to insert both files (Registry.cpp and RegMFC.cpp) into your project, but to exclude Registry.cpp from build.
In a non-MFC build you have to include Registry.cpp into your project only. In this case you don't need RegMFC.cpp.
Normally Registry.h detects whether you build an MFC version or not. If you want to build a non-MFC version in all circumstances, you can #define _REG_NO_MFC_BUILD.
Furthermore you can #define _REG_NO_TREEWALK to shrink the size of the resulting object files. This #define hides the CRegistry::RegistryTreeWalk() function and its associates. Use the _REG_NO_TREEWALK if you sure know, that you don't need the RegistryTreeWalk() method and want to reduce the code of your application/dll.
If you plan to use the CRegistry class in a non-MFC project you really should #define STRICT to make sure the class behaves correct in all circumstances. This is absolutly necessary, if you insert the class in a non-MFC dll that might be used in a MFC application.
CRegistry now is ready for use with UNICODE.

Changes in Revision 3

  • The RegistryTreeWalk() method no longer reports a wrong  "depth" to the methods OnValueHit() and OnKeyHit().
  • The member USHORT m_usDepth was deleted
  • eliminated a memory leak in DeleteKey()  (thanks to Tobias Krueger)
  • several bugfixes in DeleteKey() (sent in by Tobias Krueger)

 Changes in Revision 4

  • Some of the CRegVal::SetValue() methods changed. Most changes are for UNICODE applications (allocated too less memory). CRegVal::SetValue(const CStringArray &) is the only method that changes even for non-UNICODE applications. If you write CStringArrays to the registry, you really should upgrade to this revision!

Changes in Revision 5

  • Bug fixed in the RegTreeWalk-function (thanks to Pieter E. Roos and Daniel G. Hyams): The RegEnumValue()  function returns the number of bytes read in the last parameter. Since that value is stored in the CRegVal helper class, the next time RegVal was used to receive information from RegEnumValue(), RegEnumValue() thought that the buffer that it can put data in is smaller than it really is.
  • The sample is now a VC 6 project (sorry to all of you, who have only older versions of VC - but I have to be up to date ...)

Usage

If you want to use the class in a MFC environment, you have to include all three files to your project, but to exclude Registry.cpp from build. To do so, right-click the file in the FileView of the workspace window and select Settings ... . Make sure you select All Configurations. Now select the General page and check the field Exclude file from build.
In a pure Win32 project you will need Registry.[h|cpp] only.

CRegistry consists of three files:
Registry.h
Registry.cpp
RegMFC.cpp
Download Source 12 KB
Download Sample Project 28 KB

Date Last Updated: February 3, 1999



Comments

  • Leter du etter din skjønnhet–GHD Metallic collection

    Posted by carpinteyrorch on 06/14/2013 07:13am

    [url=http://www.rettetangnorgenews.net/]CHI rettetang[/url] Så stor er etterspørselen etter rosa ghd at i oppløpet til festlig sesong, selgere på eBay er i stand til å kreve så mye som £ 200 for en rosa ghd. Som er en heidundrende £ 65 over anbefalt utsalgspris for rosa ghd! Som sådan, ettersom rosa ghd hjelper skaffe midler, kan dette være en avgjørende faktor i folks kjøper valg. Men kanskje en viktigere årsak er at et stort antall kvinner elsker rosa ting. Følgelig er det ingen stor overraskelse at når ghd brakt ut rosa ghd, ville det være noe som de ville drepe for å eie! [url=http://www.rettetangnorgenews.net/]rettetang ghd[/url] Så stor er etterspørselen etter rosa ghd at i oppløpet til festlig sesong, selgere på eBay er i stand til å kreve så mye som £ 200 for en rosa ghd. Som er en heidundrende £ 65 over anbefalt utsalgspris for rosa ghd! Som sådan, ettersom rosa ghd hjelper skaffe midler, kan dette være en avgjørende faktor i folks kjøper valg. Men kanskje en viktigere årsak er at et stort antall kvinner elsker rosa ting. Følgelig er det ingen stor overraskelse at når ghd brakt ut rosa ghd, ville det være noe som de ville drepe for å eie! [url=http://ghdrettetangtilbud.moonfruit.com/]ghd rettetang tilbud[/url] Du kan også lufttørke håret. Dette tar selvsagt mye lenger tid, men det er mye bedre for håret. I mens håret tørker naturlig kan du gre igjennom det gjevnlig, da blir håret mye rettere enn om du bare skulle latt det tørke vanlig!Alt du trenger å gjøre for å krølle meg håret med en GHD hår rettetang er dele det ved hjelp av klipp- og bånd og begynne fra det nederste laget av håret på den ene siden av hodet. Ved hjelp av en av disse GHD skjønnhetsprodukter som er om lag en tommers bredt bør nok.

    Reply
  • The Beats Pill at ramme butiks Flere funktioner omfatter

    Posted by wherewanzi on 06/05/2013 09:13pm

    [url=http://kbhretelefonerbillig.webstarts.com/]Køb høretelefoner billig[/url] Based hovedtelefoner tilbyde lydkvalitet, der er lige så forbløffende. Ideel til nutidens digitale musik, disse hovedtelefoner giver dyb bas, en fed mellemtone, og klar, uforvrænget diskant, så du kan høre hver detail.The on-ear, lukket-back design giver langvarig komfort og en høj grad af naturlig støj isolation . Den enkeltsidede kabel er designet til at give dig masser af slæk mens modstå tangles. Integreret i kablet er Monsters ControlTalk modul, som giver dig en kontrolknap og high-grade mikrofon, ideel til styring musikafspilning, telefonopkald og tage stemmenotater på kompatible iPods, iPhones, og Blackberrys. Den guldbelagt 3,5 mm stik giver bred kompatibilitet med MP3-afspillere, cd-afspillere, computere og meget mere. [url=http://www.nyebeatsbydrdre.350.com/]Nye beats by dr dre[/url] Beats By Dre blev født ud af et behov for at genoprette den følelsesmæssige forbindelse med musik, der gik tabt ved nedbrydning af lyden fra den digitale musik revolution, startende med det svageste led i oplevelsen ved time-hovedtelefoner, “sagde Beats President og COO , Luke Wood. “Men det var aldrig om bare hovedtelefoner. Vi har siden udvidet Beats mission til hver anden link i musikoplevelsen kæde – højttalere, mobiltelefoner, pc’er og bil lydsystemer. Med MOG, vi tilføjer den bedste musiktjeneste til Beats portefølje for den første ægte end-to-end musikoplevelse. Med deres talent og teknologi, er mulighederne omkring fremtidig innovation endeløs. [url=http://kbhretelefonerbillig.webstarts.com/]beats høretelefoner[/url] Det kan ikke være potentiel, at du er en total musik-freak, og du måske ikke tænker højtydende trådløse hovedtelefoner! Disse gadgets er de korrekte kammerater specielt inde du lytter til musik bestræbelser. Der er en række organisationer, først og fremmest de velkendte mærker, som Sony, Philips og Samsung osv., der tilfældigvis er i massiv organisering af elektroniske varer og tjenesteydelser og hovedtelefoner med Monstor Diddybeats White trådløse bestemmelser er en af dem. Du vil finde bestemte funktioner og faktorer, som har at blive alvorligt tages i betragtning, når 1 vælger denne fantastiske enhed. Målet er normalt at støde på en sund god kvalitet, der er helt sikkert virkelig vidunderlig og afslappende mod sindet også.

    Reply
  • hva vi fÃ¥r fra beats hodetelefoner

    Posted by mantouhmmm on 06/03/2013 10:09pm

    [url=http://www.beatsbynopro.manifo.com/]Beats By Dre[/url] Mp3-filer kan kjøpes for billige priser. De tilbyr også gratis nedlastinger for de som ønsker å teste det ut. I-Doser gir informasjon om de riktige hodetelefoner til bruk og hva slags innstilling du må være i for å få de beste effektene fra den. Den binaural beats linken nedenfor gir mer informasjon om emnet, samt gratis dataprogram og hvor du får gratis lyder mellom.Dette syv trinn formelen er prosessen med å lage beats. Beat gjør er ikke rocket science. Ved å forstå de grunnleggende prinsipper og begreper i musikkproduksjon, bør du være i stand til å gå gjennom hele prosessen med letthet og enkelhet. Akkurat som baking, musikk har sin egen formel for utvikling av en song.All musikk programmer har en lyd editor som hjelper deg i din musikk arrangement av lyder. Enten du bruker samples eller lage din egen lyd, vil du bruke en lyd editor for å skrive alle dine Beats By Dre Pro. Få en grunnleggende forståelse av hvordan musikken programvaren fungerer før du bruker denne formelen. [url=http://www.beatshodetelefoner.webstarts.com/]beats by dre norge[/url] for cheap. Even super producer Rocwilder has a beat website where artists come to purchase beats. If an artist is working on a small budget, it is most likely a better option to buy their instrumentals online.The online beat market is expanding daily, and there are literally hundreds of thousands of producers trying to sell their beats. This is bad for producers, but great for artists. There is such a wide variety of talent and option to choose from, the styles are endless. While there is a lot of saturation when attempting to shop for instrumentals in the online environment, it is not hard to find a talented producer.Buying beats online is also the most convenient approach when shopping for instrumentals for a release. Good producers are hard to get in contact with, and very good producers are impossible to contact and for good reason. A producer with beats for sale online can be accessed 24 hours a day. You can shop on your own schedule, even at two in the morning. [url=http://www.drebeatsnorge.qsite.dk/]beats by dre norge[/url] dette er lett å finne fra ulike nettsteder som har blitt prøvd og testet over tid. De trommerytmer er en viktig og en svært viktig del av beats samling uansett hva slags valdet du skriver skal de rap beats eller Jazz slår trommer er veldig viktig siden de gir en god følelse til composition.Visit ulike nettsteder og prøve litt av beats som er der og lytte til dem og prøve hva som tilbys. Besøke nettsteder som tilhører de ulike musikkproduksjon skoler for noen tips som hjelper deg i å kombinere din gratis rap beats og andre musikksjanger beats. Å kunne laste ned beats på nettet en av hemmelighetene er å slå sammen flere e-postlister som slår nedlasting nettsteder de vil gi deg siste nytt om downloads.

    Reply
  • This class is not thread safe. Wait for Revision 6.

    Posted by mmoore on 04/29/2009 02:15pm

    In http://msdn.microsoft.com/en-us/library/ms724836(VS.85).aspx we find this: "The predefined handles are not thread safe. Closing a predefined handle in one thread affects any other threads that are using the handle." This means that it is not legitimate to call RegCloseKey on a predefined handle such as HKEY_LOCAL_MACHINE, but this class will do that if you create a class object with a predefined key. This causes intermittent failures of registry access in other threads of the same application. We are trying to notify the author of this problem and we are confident he will shortly provide revised code.

    • Work-around until Revision 6.

      Posted by KevinSorensen on 04/29/2009 02:26pm

      In the meantime we do the following before every RegCloseKey( hKey_p ) call:
      
      if (!IsPredefined( hKey_p ))
         RegCloseKey( hKey_p );
      
      Where IsPredefined is the following:
      BOOL CRegistry::IsPredefined( HKEY hKey )
      {
         return ((hKey == HKEY_CLASSES_ROOT) ||
                 (hKey == HKEY_CURRENT_CONFIG) ||
                 (hKey == HKEY_CURRENT_USER) ||
                 (hKey == HKEY_LOCAL_MACHINE) ||
                 (hKey == HKEY_PERFORMANCE_DATA) ||
                 (hKey == HKEY_PERFORMANCE_NLSTEXT) ||
                 (hKey == HKEY_PERFORMANCE_TEXT) ||
                 (hKey == HKEY_USERS));
      }

      Reply
    Reply
  • Question marks at end of retrieved strings

    Posted by Bob H on 11/06/2006 12:02pm

    I am getting question marks at the end of retrieved strings. I believe it is only occurring when the build is unicode. Example: // value is set sValue = m_sPrevFontName; // value is "Arial" User.SaveKey(sKey, TEXT("PrevFontName"), sValue); // value is retrieved if (User.LoadKey(sKey, TEXT("PrevFontName"), sValue)) m_sPrevFontName = sValue; now sValue is "Arial???????"

    Reply
  • Why can't i get REG_DWORD (Numbers) data from the registry?

    Posted by Legacy on 07/15/2002 12:00am

    Originally posted by: Thorin

    I can get strings from the registry but not numbers... any clues as to why?? Or is there any way i can convert CRegVal to an int?

    Reply
  • Great Job

    Posted by Legacy on 05/24/2002 12:00am

    Originally posted by: Douglas Brook

    I just wanted to get one key out of the HKEY_LOCAL_MACHINE key and I was banging my head against my desk trying!
    
    

    Then I searched the web, found this class, installed it and literally one minute later I had my key.

    Reply
  • Unable to do RegTreeWalk Walkin

    Posted by Legacy on 12/13/2001 12:00am

    Originally posted by: Will'o the Wisp

    Well im not able to get a Tree...
    i.e.: Im Checking HKEY_CURRENT_USER

    Software\\ANY

    this key has 2 subkeys (any1 and any2)... i want to read
    them out so that i can save them in a temp string to
    call them later please help!

    thanx!

    Reply
  • Can I use CRegistry class in Windows CE?

    Posted by Legacy on 12/28/2000 12:00am

    Originally posted by: Rex Valderama


    How can i port this class in Windows CE environment? I was trying to include the files in a project and some Functions are not supported by WinCE.
    Any help would be appreciated.

    Reply
  • Resource not being freed.

    Posted by Legacy on 09/29/2000 12:00am

    Originally posted by: Sanjeev Kapoor

    There is a memory leak in CRegistry ::RegTreeWalk, you need to insert the following line
    
    

    RegCloseKey( hKey_p ) ; // SK 290900

    at about line 337, if OnKeyHit() breaks the tree walk.

    Otherwise, I am glad to download these classes for my work.

    Gute Arbeit!

    Sanjeev Kapoor

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • CentreCorp is a fully integrated and diversified property management and real estate service company, specializing in the "shopping center" segment, and is one of the premier retail service providers in North America. Company executives travel a great deal, carrying a number of traveling laptops with critical current business data, and no easy way to back up to the network outside the office. Read this case study to learn how CentreCorp implemented a suite of business continuity services that included …

Most Popular Programming Stories

More for Developers

RSS Feeds