user666491
user666491

Reputation:

Accessing windows registry under GCC/C++

I'm trying to access windows registry using standard windows api. I'm using mingw c++ compiller.

Please tell why this code crases at line (X)

HKEY hKey;
DWORD dwDisp = 0;
LPDWORD lpdwDisp = &dwDisp;

QString value = "String Value";

LONG iSuccess = RegCreateKeyEx(
      HKEY_CURRENT_USER,
      TEXT("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"),
      0L,
      NULL,
      REG_OPTION_NON_VOLATILE,
      KEY_ALL_ACCESS,
      NULL,
      &hKey,
      lpdwDisp);

if(iSuccess == ERROR_SUCCESS)
{
(X)    RegSetValueEx(hKey, TEXT("1234"), 0, REG_SZ, (LPBYTE)4, 4+1);
}

Debugger shows Segmantation fault at this line.

Thank you very much for help. I'm new to windows API.

Upvotes: 1

Views: 2397

Answers (3)

Emil H
Emil H

Reputation: 40240

Take a look at the function description again.

If you want to set the default value for the key you need to do something like this:

TCHAR szData[] = TEXT("1234")
RegSetValueEx(hKey, NULL, 0, REG_SZ, (LPBYTE)szData, sizeof(szData));

If you actually want to specify the value name:

TCHAR szData[] = TEXT("1234")
RegSetValueEx(hKey, TEXT("valuename"), 0, REG_SZ, (LPBYTE)szData, sizeof(szData));

The registry has a somewhat confusing terminology. The key in this context basically means "folder". Each folder has a default value, and can contain other values with specified names. You pass null if you want to set the default value, and a string if you want to name the value. These values shows up as "files" in the key "folder" when you look in the register editor.

Upvotes: 2

Sebastian Dusza
Sebastian Dusza

Reputation: 2528

Remove HKEY_LOCAL_MACHINE\ from the second parameter and it should work fine. HKEY_LOCAL_MACHINE should be set in the first param.

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283634

Casts are bad.

What do you expect (LPBYTE)3 to do? Why do you think you need it?

Isn't that where value should be used? Perhaps as value.ascii() or value.constData() (depending on whether UNICODE is defined)? (NOTE: QString value mysteriously disappeared from the question)

Upvotes: 2

Related Questions