Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C++
Article

A handy class to make use of Windows Registry

Rate me:
Please Sign up or sign in to vote.
3.81/5 (18 votes)
15 Aug 20043 min read 88.5K   1.9K   28   21
Shows how simple accessing Windows Registry can be if you do not need bells and whistles.

Sources update

The sources have been updated. (Hopefully) This will make them compilable on VC 7+. I couldn't test it with VC 7, but I expect it will be OK now. For more info take a look what was the problem.

New Additions

This class has been modified:

  • Improved internal logic.
  • Improved support for writing structured data to registry.
  • Added possibility to see internal execution flow (e.g., when data is read from and written to the registry).
  • Added support for HKEY_LOCAL_MACHINE, HKEY_USERS, and all the others...

In short, in order to store a structure in registry, you only need to do like this:

SomeStruct X;
//set struct values...
reg["SomeStructData"].set_struct(X);

In order to read back the stored structure:

SomeStruct X;
//set struct values...
if(reg["SomeStructData"].get_struct(X)){
    //Ok, X contains the read data...
}else {
    //error reading struct.
}

In order to use HKEY_LOCAL_MACHINE or other, you can pass a second parameter of type registry::Key to the registry constructor:

registry reg("Sowtware\\Whatever",registry::hkey_local_machine);

The second parameter is optional, it defaults to registry::hkey_current_user.

In order to see internal execution flow, you may #define WANT_TRACE. And in console mode, you'll see when and what objects are created, and when values read to/ written from the registry. There was added a new project with_trace to see that.

//with trace

#define WANT_TRACE //define this to be able to see internal details...

#include "registry.h"
#include "string.h"
#include <STRING>

struct Something{
    int area;
    float height;
};

int main(int, char*)
{
    registry reg("Software\\Company");
    {
        Something X;
        X.area=100;
        X.height=4.5;

        reg["Something"].set_struct(X);
    }
    Something Z;
    if(reg["Something"].get_struct(Z)){
        printf("area is: %i\nheight is: %f\n", Z.area,Z.height);
    }

    return 0;
}

It produces the following output:

with_trace output

Introduction

First of all, you need only one file registry.h, that's included in the source distribution. Read on...

//Dirty and fast howto

#include "registry.h"
#include "string.h"

int main(int, char*){

    registry reg("Software\\Company");
    reg["Language"]="English";        //set value
    reg["Width"]=50;
    printf("The address is: %s\n",(char*)reg["Address"]); 
    //prints nothing unless you put something in
    return 0;
}

A more descriptive howto:

//Long story:

#include "registry.h"
#include "string.h"

struct ServerAddress{
    char name[64];
    char ip[15];
    short port;
};

int main(int,char*){

    //first step is to create our home registry 
    //record(or open it if exists)
    //the constructor accepts a string and if you do:
    registry settings("Software\\MyCoolApp");
    //you open HKEY_CURRENT_USER\Sowtware\MyCoolApp

    //Due to simplicity this class is desined to deal with only 
    //HKEY_CURRENT_USER registry group. 
    //You may, however, modify this behavior if you need

    //To make sure that the home key has been created or 
    //opened you can test it like this:

    if(!settings){
        //error code goes here...
        exit(1);
    }

    //The next step is to create (or open if exists) 
    //a value key:
    //the official way is like this: (for another, 
    //simpler way, read below.)

    registry::iterator lang=settings["Language"];    
    //Personally I don't use it this way - too much to type...

    //and then you can retrive value of "Language" key 
    //as follows:

    printf("The selected language is: \"%s\"\n",(char*)lang);

    //if you want to modify a value you can do simply like this:

    lang="Russian";

    //Internally this class stores values as 
    //binary data and therefore 
    //you are not limited to strings only.

    // Example:

    ServerAddress MyCoolServer;
    strcpy(MyCoolServer.name,"somewhere.example.com");
    strcpy(MyCoolServer.ip,"192.168.0.1");
    MyCoolServer.port=1024;

    //now let's put this record into registry key "server"
    //it can be simply done like this:

    registry::iterator server=settings["server"];
    server=string((const char *)(&MyCoolServer),sizeof(MyCoolServer));

    //now let's test by retriving the structure back:

    ServerAddress serAdr;
    const string &FromRegistry=server;
    //copy data only if it's of the size of the struct ServerAddress
    if(FromRegistry.length()==sizeof(ServerAddress)){        
        memcpy(&serAdr,FromRegistry.c_str(), sizeof(ServerAddress));
        //now let's see what we have (see a pic below):
        printf("Print out for my server:\n");
        printf("\tserver's host name is:  %s\n",    serAdr.name);
        printf("\tserver's ip address is: %s\n",    serAdr.ip);
        printf("\tserver's port is:       %u\n\n",  serAdr.port);
    }else{
        //error code goes here...
    }
    return 0;
}

Sample Image - long_story.jpg

Pic.1 Output from a more descriptive howto.

I coded these few lines with simplicity in mind. I like the style, when I can assign value to a registry key as to a usual variable. I will describe shortly how I use this code in my projects. I put a member variable reg (instance of registry) to my app's class (there is a reason, read below) that needs access to the registry. Then, in the class' constructor, I instantiate reg variable to the registry home key. Since there is no default constructor in the registry class, you may do it like this:

class my_app{
protected:
    registry reg;
    string UserName;
public:
    my_app() : reg("Software\\my_app"){ // <--
        UserName = reg["UserName"]; //read value
    }
    ~my_app(){
        //store value back to the registry
        reg["UserName"] = UserName;
    }
}

In the preceding line, you actually don't need to create a separate string for UserName - you may have a member variable of registry::iterator type, that will be automatically stored to the registry when your class is destructed (see the final example at the bottom of the page).

And then, whenever you need, you can do like this:

SetLanguage(reg["Lang"]); 
string UserName=reg["User"];

that's really simple...

Background

Now, a little background on how it works internally. This is actually a very lightweight class. It makes less API calls than you would probably do.

For example, the line:

reg["Something"]="nothing";

will only once physically access registry on destruction of the returned key-value to assign value "nothing" to key "something".

Same happens with the next lines (only one API call when the group goes out of scope):

registry::iterator name=settings["UserName"];
name="John";
name="Alex";
name="Someone Else";

Basically, if you intend to use this class, you should be aware that statement reg["something"]="nothing"; doesn't modify anything in registry by itself. The value will be set only when the statement goes out of scope, like this:

{
    reg["UserName"]="Bill";
    printf("The username is: %s\n", (char*)reg["UserName"]); 
    //!!WILL NOT PRINT BILL, 
    //it will print the value that was before the previous line
}//at this point the value Bill is in the registry
printf("The username is: %s\n", (char*)reg["UserName"]); //now it prints Bill;

In order to force it to commit to the registry at some point, you can use flush() method like this:

registry::iterator name=settings["UserName"];
name="John";
name.flush(); //at this point it will write value "John" to registry.

The same applies to reading values - they are retrieved only when you request them, and only once! So, if you know (or think) that something else (perhaps Earth's magnetic field :)) has modified a key's value, you may use refresh() method. But, be carfull!! Anything you have assigned before will not be committed (it's overwritten by the returned value from registry).

And a very important point. When the instance of registry is destructed, or goes out of scope, then all the values you created from it will not have access to the registry. That is, all iterators on a given registry instance should be destructed before their parent registry instance. That's why I use this class as a member of another class. When the parent class is destroyed, it doesn't need access to the registry, neither is it possible at that point.

That's it. Hope it will be useful to someone.

A better example

#include "registry.h"
#include <iostream>


class my_app{
protected:
    registry reg;
    registry::iterator UserName;
public:
    my_app():reg("Software\\Company"),UserName(reg["UserName"]){}
    ~my_app(){}
    void SetUserName(const char * name){
        UserName = name;
    }
    const char * GetUserName(){
        return (const char *) UserName;
    }
};

int main (int, char *){
    my_app App;
    App.SetUserName("Alex");
    cout<<"The username is: "<<App.GetUserName()
        <<endl<<"Thanks for playing..."<<endl;
    return 0;
}

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


Written By
Canada Canada
Big Grin | :-D

Comments and Discussions

 
Generalnumber of values in a key Pin
Mbarki25-Apr-07 23:33
Mbarki25-Apr-07 23:33 
GeneralRe: number of values in a key Pin
__PPS__27-Apr-07 12:20
__PPS__27-Apr-07 12:20 
GeneralSource does not work with STLPORT Pin
RalfGriggel27-Nov-06 4:39
RalfGriggel27-Nov-06 4:39 
GeneralRe: Source does not work with STLPORT Pin
__PPS__27-Nov-06 5:57
__PPS__27-Nov-06 5:57 
Generalsources not working on restricted user Pin
dimmudimmu17-Mar-06 0:51
dimmudimmu17-Mar-06 0:51 
GeneralRe: sources not working on restricted user Pin
__PPS__17-Mar-06 4:32
__PPS__17-Mar-06 4:32 
GeneralUNICODE support Pin
CrystalPaul8-Dec-05 17:29
CrystalPaul8-Dec-05 17:29 
GeneralRe: UNICODE support Pin
__PPS__8-Dec-05 22:32
__PPS__8-Dec-05 22:32 
GeneralSetting default value on first use. Pin
neticous13-Jun-05 19:31
neticous13-Jun-05 19:31 
GeneralRe: Setting default value on first use. Pin
neticous14-Jun-05 3:01
neticous14-Jun-05 3:01 
Generalreally great, just one thing missing... Pin
Tiago10-Nov-04 5:28
Tiago10-Nov-04 5:28 
Generalreally easy to use, great article! thanks pps Pin
Robert Space14-Sep-04 23:30
Robert Space14-Sep-04 23:30 
GeneralRe: really easy to use, great article! thanks pps Pin
Robert Space14-Sep-04 23:43
Robert Space14-Sep-04 23:43 
GeneralRe: really easy to use, great article! thanks pps Pin
__PPS__15-Sep-04 13:39
__PPS__15-Sep-04 13:39 
GeneralMain doesnt compile Pin
CRWeaks2312-Aug-04 9:12
CRWeaks2312-Aug-04 9:12 
GeneralRe: Main doesnt compile Pin
Anonymous14-Aug-04 17:12
Anonymous14-Aug-04 17:12 
GeneralRe: Main doesnt compile Pin
__PPS__14-Aug-04 18:46
__PPS__14-Aug-04 18:46 
GeneralImplementation details Pin
Johann Gerell14-Jun-04 1:22
Johann Gerell14-Jun-04 1:22 
GeneralRe: Implementation details Pin
__PPS__14-Jun-04 1:34
__PPS__14-Jun-04 1:34 
GeneralRe: Implementation details Pin
Johann Gerell14-Jun-04 3:02
Johann Gerell14-Jun-04 3:02 
GeneralRe: Implementation details Pin
__PPS__14-Jun-04 4:16
__PPS__14-Jun-04 4:16 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.