Solved

Need to create registry hive under (HKLM) in W/NT

Posted on 2000-03-16
12
707 Views
Last Modified: 2012-06-21
I need to create a registry hive in Windows NT under HKLM. I get an error trying to write to the registry. How, and what code can I use to get past this problem? Do I need to call an API? if so how and could you please illustrate. Also am I able to have the program call a .reg file to make the changes?
Thanks
Pote
0
Comment
Question by:pote
  • 3
  • 3
  • 3
  • +1
12 Comments
 
LVL 7

Expert Comment

by:tchalkov
ID: 2623696
You. first of all need to be an administrator to write to HKLM.

If you can't do it through Registry Editor, then you can't do it with a program too.

If you are an administrator, then there are a few ways to do this.

1. Create a reg file, and execute it trhough ShellExecute

2. Use the Reg... API (RegCreateKey etc.). If you choose this way and need an exmaple on this I can send you.
0
 

Author Comment

by:pote
ID: 2623720

Actually yes, I will need an example of using the Reg...API(RegCreateKey etc..)
Thanks for your help..
Pote
0
 
LVL 7

Expert Comment

by:tchalkov
ID: 2623761
Here is a sample class for registry access. It is far from perfect(a friend wrote it while learning the API), but it demonstrates the nasic use of Reg... API.

For Creating keys and values see the setposition and setkey functions.

#include "stdafx.h"
#include "windows.h"
#include "winerror.h"
#include "shlwapi.h"
//this convert char* to unsigned char*
#define char2unsigned(x) ((unsigned char *) x)

#define DEBUG_CREG

#ifdef DEBUG_CREG
#include "iostream.h"
#define ERRORMSG(X) OutputDebugString("\nerreor\tX1")
#endif

class CReg
{
      unsigned int len ( register const unsigned char * a)
      {
            for (register unsigned int i=0;*(a+i);++a,++i);
            return i+1;
      }
protected:
      HKEY curpos;
public:
      CReg(HKEY key=HKEY_CLASSES_ROOT):curpos(key){}      
      virtual ~CReg()//this may be to save unsaved key or value in registry
      {
            try
            {
            long res=::RegCloseKey(curpos);
            if (!(res==ERROR_SUCCESS));
            }
            catch(...)
            {
                  ERRORMSG(1);
            }

      }
      HKEY setposition(HKEY key) { return curpos=key;}
      //--------------------
      //this function for save String value
      int setvalue(const unsigned char * val,const char * nameval,HKEY pos=0)
      {
            try
            {
            long errcode=::RegSetValueEx ((pos?pos:curpos),nameval,0,REG_SZ,val,len(val)+1);
            if (errcode==ERROR_SUCCESS)
                  return 0;
            return 1;
            }
            catch(...)
            {
                  ERRORMSG(2);
            }
      }
      //--------------------
      //this function for save a DWORD value 32 bit number
      int setvalue( unsigned int  val,const char * nameval,HKEY pos=0)
      {
            try
            {
            long a=a/0;
            long errcode=::RegSetValueEx ((pos?pos:curpos),nameval,0,REG_DWORD, (const unsigned char *)&val,sizeof(unsigned int));
            if (errcode==ERROR_SUCCESS)
                  return 0;
            return 1;
            }
            catch(...)
            {
                  ERRORMSG(3);
            }
      }
      //--------------------
      //this fuction for save a BINARY value with size
      int setvalue(const unsigned char * val,const char * nameval,unsigned int size,HKEY pos=0)
      {
            try
            {
            long errcode=::RegSetValueEx ((pos?pos:curpos),nameval,0,REG_BINARY,val,size);
            if (errcode==ERROR_SUCCESS)
                  return 0;
            return 1;
            }
            catch(...)
            {
                  ERRORMSG(4);
            }
      }
      //create simple key
      HKEY setkey(char * namekey,HKEY key=0);
      HKEY setposition(char *namekey,HKEY key=0)
      {
            try
            {
                  HKEY k;
                  ::RegOpenKeyEx((key?key:curpos),namekey,0,KEY_ALL_ACCESS,&k);
                  curpos=k;
                  return k;
            }
            catch(...)
            {
                  ERRORMSG(5);
            }
      }
      long delvalue(char * nameval,HKEY key=0)
      {
            try
            {
                  return ::RegDeleteValue((key?key:curpos),nameval);
            }
            catch(...)
            {
                  OutputDebugString("\nerreor\n");
            }
      }
      long delkey(char * name,HKEY key=0)
      {
            try
            {
                  DWORD er=::RegDeleteKey((key?key:curpos),name);
                  if (!(er==ERROR_SUCCESS))
                  {
#ifdef DEBUG_CREG
                        cout <<"The key is not empty";
#endif
                  //if Win ÍÒ
                        er=::SHDeleteKey((key?key:curpos),name);
                        if(!(er==ERROR_SUCCESS)) er=::SHDeleteEmptyKey((key?key:curpos),name);
                  }
                  else
                  {
#ifdef DEBUG_CREG
                        cout <<"The key is empty";
#endif
                  }
                  return er;
            }
            catch(...)
            {
                  ERRORMSG(5);
            }
      }
};

HKEY CReg::setkey(char * namekey,HKEY key)
{
            
      try
      {
            DWORD what;                        
            key=(key?key:curpos);
            long errcode=::RegCreateKeyEx(key,namekey,0,0,REG_OPTION_VOLATILE,KEY_ALL_ACCESS,0,&curpos,&what);
            
#ifdef DEBUG_CREG
            if (what==REG_CREATED_NEW_KEY)
                  cout <<"\nnew key";
            else
                  cout <<"\nold key";
#endif
            /*if (errcode==ERROR_SUCCESS)
                  return 0;
            return 1;*/
            return curpos;
      }
      catch(...)
            {
                  ERRORMSG(5);
            }
}




int main(int argc, char* argv[])
{
#ifdef DEBUG_CREG
      CReg a=HKEY_CURRENT_USER;
      
      a.setkey ("opit key\\opit2");
      a.setvalue(355,"opit pri syzdavane na moj key");
      a.setvalue (char2unsigned("opit"),"opit");
      a.setvalue (23,"opitint");
      a.setvalue (char2unsigned("binary"),"binary",2);
      a.delvalue("binary");
      a.setposition (HKEY_CURRENT_USER);
      a.delkey ("opit key");
#endif
      return 0;
}

0
 
LVL 5

Expert Comment

by:Wyn
ID: 2623770
Hi ,pote .
Here is a sample code ,you can simply replace the key name for your need:)


    LONG    lResult;
    HKEY    hRegKey;
    DWORD   nDispos;

    lResult = RegCreateKeyEx(
                HKEY_CLASSES_ROOT,      // handle of an open key
                "my new group",         // address of subkey name
                0,                      // reserved
                "",                     // address of class string
                0,                      // special options flag
                KEY_ALL_ACCESS,         // desired security access
                NULL,                   // address of key security structure
                &hRegKey,               // address of buffer for opened handle
                &nDispos                // address of disposition value buffer
           );

    if (lResult==ERROR_SUCCESS)
    {
        //-- 1. store a number
        DWORD nValue;

        nValue = 123;

        lResult = RegSetValueEx(
                hRegKey,        // handle of key to set value for
                "MyIntegerKey", // address of value to set
                0,              // reserved
                REG_DWORD,      // flag for value type
                (const BYTE*)&nValue,        // address of value data
                sizeof(DWORD)   // size of value data
               );

        //-- 2. store a string
        char *txt = "Hello World!";

        lResult = RegSetValueEx(
                hRegKey,        // handle of key to set value for
                "MyStringKey",  // address of value to set
                0,              // reserved
                REG_SZ,      // flag for value type
                (const BYTE*)txt,        // address of value data
                strlen(txt)+1   // size of value data
               );


        RegCloseKey(hRegKey);
     }

0
 

Author Comment

by:pote
ID: 2623870
I'll give both examples a try, and respond whit results/
Thanks
0
 

Author Comment

by:pote
ID: 2625180
I've tried both examples.
None work for NT.
The first example from tchalkov  compiles with 3 errors, looking for unresolved externals (probably a lib file not included)
The example provided by Wyn works for Win 95 and 98, but not NT, which is what I need.
Any other suggestions
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 5

Expert Comment

by:Wyn
ID: 2626650
->The example provided by Wyn works for Win 95 and 98, but not NT, which is what I need.
=======================
Nope,it works both but you must the one who can change NT reigstry(e.g:administrator),undertand me?

What problem you meet to change NT if it's not the problem above?

Free to ask
Regards
W.Yinan
0
 
LVL 7

Accepted Solution

by:
tchalkov earned 200 total points
ID: 2627514
Here is an update source code.
In order to compile you need to add shlwapi.lib to the libraries in yiur projects.

This is necessary because some actions on the system registry are easier to do through the shlwapi.dll.

Run this program as console application.

This code is tested and works under NT.

If you still have problems under NT, debug the program, and tell me the eror codes you recieve.

#include "windows.h"
#include "winerror.h"
#include "shlwapi.h"
//this convert char* to unsigned char*
#define char2unsigned(x) ((unsigned char *) x)

#define DEBUG_CREG

#ifdef DEBUG_CREG
#include "iostream.h"
#define ERRORMSG(X) OutputDebugString("\nerreor\tX1")
#endif

class CReg
{
      unsigned int len ( register const unsigned char * a)
      {
            for (register unsigned int i=0;*(a+i);++a,++i);
            return i+1;
      }
protected:
      HKEY curpos;
public:
      CReg(HKEY key=HKEY_CLASSES_ROOT):curpos(key){}
      virtual ~CReg()//this may be to save unsaved key or value in registry
      {
            try
            {
                  long res=::RegCloseKey(curpos);
            }
            catch(...)
            {
                  ERRORMSG(1);
            }
            
      }
      HKEY setposition(HKEY key) { return curpos=key;}
      //--------------------
      //this function for save String value
      int setvalue(const unsigned char * val,const char * nameval,HKEY pos=0)
      {
            try
            {
                  long errcode=::RegSetValueEx ((pos?pos:curpos),nameval,0,REG_SZ,val,len(val)+1);
                  if (errcode==ERROR_SUCCESS)
                        return 0;
                  return 1;
            }
            catch(...)
            {
                  ERRORMSG(2);
                  return 1;
            }
      }
      //--------------------
      //this function for save a DWORD value 32 bit number
      int setvalue( unsigned int  val,const char * nameval,HKEY pos=0)
      {
            try
            {
//                  long a=a/0;
                  long errcode=::RegSetValueEx ((pos?pos:curpos),nameval,0,REG_DWORD, (const unsigned char *)&val,sizeof(unsigned int));
                  if (errcode==ERROR_SUCCESS)
                        return 0;
                  return 1;
            }
            catch(...)
            {
                  ERRORMSG(3);
            }
      }
      //--------------------
      //this fuction for save a BINARY value with size
      int setvalue(const unsigned char * val,const char * nameval,unsigned int size,HKEY pos=0)
      {
            try
            {
                  long errcode=::RegSetValueEx ((pos?pos:curpos),nameval,0,REG_BINARY,val,size);
                  if (errcode==ERROR_SUCCESS)
                        return 0;
                  return 1;
            }
            catch(...)
            {
                  ERRORMSG(4);
            }
      }
      //create simple key
      HKEY setkey(char * namekey,HKEY key=0);
      HKEY setposition(char *namekey,HKEY key=0)
      {
            try
            {
                  HKEY k;
                  ::RegOpenKeyEx((key?key:curpos),namekey,0,KEY_ALL_ACCESS,&k);
                  curpos=k;
                  return k;
            }
            catch(...)
            {
                  ERRORMSG(5);
            }
      }
      long delvalue(char * nameval,HKEY key=0)
      {
            try
            {
                  return ::RegDeleteValue((key?key:curpos),nameval);
            }
            catch(...)
            {
                  OutputDebugString("\nerreor\n");
            }
      }
      long delkey(char * name,HKEY key=0)
      {
            try
            {
                  DWORD er=::RegDeleteKey((key?key:curpos),name);
                  if (!(er==ERROR_SUCCESS))
                  {
                        //if Win ÍÒ
                        er=::SHDeleteKey((key?key:curpos),name);
                        if(!(er==ERROR_SUCCESS)) er=::SHDeleteEmptyKey((key?key:curpos),name);
                  }

                  return er;
            }
            catch(...)
            {
                  ERRORMSG(5);
                  return 1;
            }
      }
};

HKEY CReg::setkey(char * namekey,HKEY key)
{
      
      try
      {
            DWORD what;
            key=(key?key:curpos);
            long errcode=::RegCreateKeyEx(key,namekey,0,0,REG_OPTION_VOLATILE,KEY_ALL_ACCESS,0,&curpos,&what);
            return curpos;
      }
      catch(...)
      {
            ERRORMSG(5);
      }
}




int main(int argc, char* argv[])
{
#ifdef DEBUG_CREG
      CReg a=HKEY_CURRENT_USER;
      
      a.setkey ("opit key\\opit2");
      a.setvalue(355,"opit pri syzdavane na moj key");
      a.setvalue (char2unsigned("opit"),"opit");
      a.setvalue (23,"opitint");
      a.setvalue (char2unsigned("binary"),"binary",2);
      a.delvalue("binary");
      a.setposition (HKEY_CURRENT_USER);
      a.delkey ("opit key");
#endif
      return 0;
}
0
 
LVL 9

Expert Comment

by:Pacman
ID: 2627876
Wyn, you dont have to be administrator under NT.
You must write the correct code ; )

pote, you must do some "security-things" to access registry fully on NT.
take a look at the following article from the microsofties:

http://support.microsoft.com/support/kb/articles/Q128/7/31.asp?LNG=ENG&SA=ALLKB&FR=0

let me know if it helped you
0
 
LVL 9

Expert Comment

by:Pacman
ID: 2627889
oops,

sorry wrong subject : )
forget my previous comment ..
(where's the trashcan ???)
0
 
LVL 9

Expert Comment

by:Pacman
ID: 2627929
Here a short overview on how to write values to registry:

First you have to get a "handle" to a key. Key is like a directory
or like a group.
You can either create a new key (group) or open an existing one.
The function for both cases is RegCreateKeyEx().

Having a valid handle to this key, you can now create new or change
existing sub-keys.
The function is RegSetValueEx()


a sample code:


    LONG    lResult;
    HKEY    hRegKey;
    DWORD   nDispos;

    lResult = RegCreateKeyEx(
                HKEY_CLASSES_ROOT,      // handle of an open key
                "my new group",         // address of subkey name
                0,                      // reserved
                "",                     // address of class string
                0,                      // special options flag
                KEY_ALL_ACCESS,         // desired security access
                NULL,                   // address of key security structure
                &hRegKey,               // address of buffer for opened handle
                &nDispos                // address of disposition value buffer
           );

    if (lResult==ERROR_SUCCESS)
    {
        //-- 1. store a number
        DWORD nValue;

        nValue = 123;

        lResult = RegSetValueEx(
                hRegKey,        // handle of key to set value for
                "MyIntegerKey", // address of value to set
                0,              // reserved
                REG_DWORD,      // flag for value type
                (const BYTE*)&nValue,        // address of value data
                sizeof(DWORD)   // size of value data
               );

        //-- 2. store a string
        char *txt = "Hello World!";

        lResult = RegSetValueEx(
                hRegKey,        // handle of key to set value for
                "MyStringKey",  // address of value to set
                0,              // reserved
                REG_SZ,      // flag for value type
                (const BYTE*)txt,        // address of value data
                strlen(txt)+1   // size of value data
               );


        RegCloseKey(hRegKey);
     }


Hope this helps you.
0
 
LVL 5

Expert Comment

by:Wyn
ID: 2628390
->Wyn, you dont have to be administrator under NT.
You must write the correct code ; )
==========================
Code has no problem as yours but as administrator maybe a wrong word.
Anyway,what problem you meet ,pote?
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now