0

I writing small application in pure C++. But now I encourage strange problem. I wanted to add my application to autostart but it not working. I use this code to access to Registry:

BOOL SetKeyData(HKEY hRootKey, WCHAR *subKey, DWORD dwType, WCHAR *value, LPBYTE data, DWORD cbData)
{
    HKEY hKey;
    if(RegCreateKeyW(hRootKey, subKey, &hKey) != ERROR_SUCCESS)
        return FALSE;

    LSTATUS status = RegSetValueExW(hKey, value, 0, dwType, data, cbData);
    if(status != ERROR_SUCCESS)
    {
        RegCloseKey(hKey);
        return FALSE;
    }

    RegCloseKey(hKey);
    return TRUE;
}

At first I thought that problem is in data that I serve, so i converted WCHAR with path to LPBYTE like this and execute this function in this way:

size_t i;
char *pMBBuffer = (char *)malloc( MAX_PATH );
wcstombs_s(&i, pMBBuffer, MAX_PATH, my_program, MAX_PATH-1 );
SetKeyData(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", REG_SZ, L"zwApplication", (LPBYTE)pMBBuffer, i))

I get status code ERROR_ACCESS_DENIED. Maybe problem is policy in Windows 7, but I thought that I have full access to everything in HKEY_LOCAL_MACHINE. How to solve this problem?

zwierzak
  • 269
  • 1
  • 4
  • 12
  • 1
    An action such as this would definately require elevated permissions "run as administrator" ?? – GHz May 20 '12 at 00:24
  • Does it give you the same status code for HKEY_CURRENT_USER as well? – J A May 20 '12 at 00:24

1 Answers1

2

Writing to HKEY_LOCAL_MACHINE requires that your app runs with elevated privileges. Which means your app would require to set this in its manifest file.

Without this, you can only write to HKEY_CURRENT_USER, or read from HKEY_LOCAL_MACHINE - but for your autostart requirement, that would work just as fine.

Stefan
  • 43,293
  • 10
  • 75
  • 117
  • Thanks, this solved my problem, now I have next. I have path to my program in WCHAR and how convert it to LPBYTE? I thought that I can use wcstombs_s, but when I write it to registry it is unreadable. – zwierzak May 20 '12 at 13:03
  • you don't have to convert the string: if you pass REG_SZ, the lpByte must point to a (wide) char string. No need to convert anything. (wide char string in case you're compiling with UNICODE, simple char string in case of ANSI) – Stefan May 20 '12 at 15:26