views:

217

answers:

3

I'm attempting to edit the registry with C++ and this is my first time trying to do so, and I'm failing. I'm not getting any error code, everything says it completed successfully, but it doesn't actually change the registry key.

Here is the code I am using:

HKEY hkey;
DWORD dwDisposition, dwType, dwSize;
int autorun = 0x00;
int CD_AUTORUN_DISABLED = 0x20;
long errorCode;
errorCode = RegOpenKeyEx(HKEY_CURRENT_USER, TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"), 0, KEY_ALL_ACCESS, &hkey);

if(errorCode == ERROR_SUCCESS) {
     dwType = REG_DWORD;
     dwSize = sizeof(dwType);
     errorCode = RegQueryValueEx(hkey, TEXT("NoDriveTypeAutoRun"), NULL, &dwType, 
(PBYTE)&autorun, &dwSize);

cout << "Autorun value: " << autorun << endl;
if((autorun & CD_AUTORUN_DISABLED) == 0x20){
  int newAutorun = (autorun - CD_AUTORUN_DISABLED);
  cout << "New value: " << newAutorun  << endl;
  errorCode = RegSetValueEx(hkey, TEXT("NoDriveTypeAutoRun"), 0, dwType, (PBYTE) &autorun, dwSize);
  if(errorCode == ERROR_SUCCESS){
   errorCode = RegCloseKey(hkey);    
   if(errorCode == ERROR_SUCCESS){
    cout << "Value changed." << endl;
   }
  }else{
   cout << "Value change failed, error code: " << errorCode << endl;
  }
 }else{
  cout << "Keep current value." << endl;
 }

}else{
 if(errorCode == ERROR_ACCESS_DENIED){
  cout << "Access denied." << endl;
 }else{
  cout << "Error! " << errorCode << " : " << ERROR_SUCCESS << endl;
 }
}

What am I doing wrong?

+2  A: 

You appear to be setting the registry key to the same value that you read it.

int newAutorun = (autorun - CD_AUTORUN_DISABLED);
                cout << "New value: " << newAutorun  << endl;
                errorCode = RegSetValueEx(hkey, TEXT("NoDriveTypeAutoRun"), 0, dwType, (PBYTE) **&autorun**, dwSize);

Should be

int newAutorun = (autorun - CD_AUTORUN_DISABLED);
                cout << "New value: " << newAutorun  << endl;
                errorCode = RegSetValueEx(hkey, TEXT("NoDriveTypeAutoRun"), 0, dwType, (PBYTE) &newAutorun, dwSize);
Darsant
oh dear.... That's not good.
Malfist
A: 

I think this:

errorCode = RegSetValueEx(hkey, TEXT("NoDriveTypeAutoRun"), 0, dwType, (PBYTE) &autorun, dwSize);

should be this:

errorCode = RegSetValueEx(hkey, TEXT("NoDriveTypeAutoRun"), 0, dwType, (PBYTE) &newAutorun, dwSize);

(look carefully at 2nd to last param)

Garrett
A: 

Try changing this:

errorCode = RegSetValueEx(hkey, TEXT("NoDriveTypeAutoRun"), 0, dwType, (PBYTE) &autorun, dwSize);

to this:

errorCode = RegSetValueEx(hkey, TEXT("NoDriveTypeAutoRun"), 0, dwType, (PBYTE) &newAutorun, dwSize);

Neal S.