views:

61

answers:

1

Hi, I've got a problem about RegOpenKeyEx, the code:

#include <tchar.h>
#include <stdio.h>
#include <windows.h>

#pragma comment (lib, "Advapi32.lib")


int main () {
    TCHAR *keyName = _T("SOFTWARE\\foobar2000\\capabilities");
    HKEY key = NULL;
    if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyName, 0, KEY_ALL_ACCESS, &key) != ERROR_SUCCESS) {
        printf("open key failed!\n");
        return -1;
    } else {
            printf("open key success!\n");
    }

    TCHAR *value = _T("123");
    if (RegSetValueEx(key, _T("xxx"), 0, REG_SZ,
            (const BYTE *)value, sizeof(TCHAR) * (_tcslen(value) + 1)) != ERROR_SUCCESS) {
        printf("set value failed!\n");
    }
    RegCloseKey(key);
    return 0;
}

Save the code in such as reg.cpp, and in command mode:

cl reg.cpp

and I got reg.exe, run it:

D:\tmp>reg.exe

open key success!

But the value hasn't been written in the registry.

Another strange thing is that if I use the visual studio to create a CLI project, and paste the code into main(), the RegOpenKeyEx() will return false.

The platform is windows 7, and UAC is enabled.

+2  A: 

Sounds like you're running into virtualization. IF the app has no manifest, when you try to write to HKLM\Software it actually writes to HKEY_USERS\<User SID>_Classes\VirtualStore\Machine\Software. To prevent this, you can run the app elevated. You might want to add a manifest forcing it to run elevated every time. Alternatively, stop writing to HKLM and use HKCU instead.

As for the C++/CLI part, my guess would be you are given an asInvoker manifest for that one, which suppresses virtualization and results in the attempt to get to HKLM failing.

Kate Gregory