Visual Studio C++ RegOpenKeyEx() registry Access is denied error Windows 7 64 bit

permission-deniedregistryvisual c++visual studio 2010windows-7-x64

I'm running a C++ program (which works great on 32 bit Win XP) on Windows 7 64 bit in debugger under Visual Studio 2010 and I am unable to open an existing registry key with the following code:

#define ACCESS  (KEY_WRITE | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS)

HKEY hKey;
long dwErrorCode = ::RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\MYTHING", 0, ACCESS|KEY_WOW64_64KEY, &hKey);

if (dwErrorCode != ERROR_SUCCESS) 
{
// display error message
}

The error code returned is: 5 with the system message being "Access is Denied".

This does work if I run the Visual Studio 2010 as Admin, however I'd rather not have to do that. Can anybody offer a suggestion?

Update: I forgot to mention, what I am doing here is porting legacy code from Windows XP. As such, I don't have the option of changing the fundamental structure of how this software was written. Since the legacy code uses the registry, that is what the ported code must do also.

Also, I would rather not make changes to my specific computer — since that means I would have to change every computer that I want to run this on. This could get messy as there are a lot of machines affected. For example, I don't want to turn off UAC for the entire machine.

Further update: I haven't found a solution that I'm happy with. Have decided to ignore error code 5 for purposes of debugging and that seems to be working well enough for now. I'm trying to understand how standard apps like Word, Firefox, etc appear to be using the registry for all kinds of settings and yet are not elevated nor do I have to give them special permissions to make changes to the registry?

Best Answer

Ok, I found the answer to my question so I'll post it here in case anybody else needs it for future reference. This thread turned out to be helpful even though it is actually on the topic of C#:

http://social.msdn.microsoft.com/Forums/da-DK/netfx64bit/thread/92f962d6-7f5e-4e62-ac0a-b8b0c9f552a3

Basically, I needed to change my permission to read the 32 bit registry instead of the 64 bit one like so:

HKEY hKey;
long dwErrorCode = ::RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\MYTHING", 0, ACCESS|KEY_WOW64_32KEY, &hKey);

if (dwErrorCode != ERROR_SUCCESS) 
{
// display error message
}

Voila, everything works now! Thanks for your efforts everyone.

Update: it turns out this didn't work as well on my other machine, which led me to discover that someone must have changed access rights to the 32 bit registry on one of my machines. So it is still necessary to give the User access rights to the registry key you want to work with.