Search code examples
c++windowsregistry

Reading the Windows registry key "SOFTWARE\Microsoft\Windows\CurrentVersion\Run" using RegGetValue() returns error code 2


Reading the Windows registry key "SOFTWARE\Microsoft\Windows\CurrentVersion\Run" using RegGetValue() returns error code 2.

I've been sitting for hours debugging this problem, but haven't found a solution.

Here is the code that I use to retrieve the registry value named "test":

long result = RegGetValue(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"), TEXT("test"), RRF_RT_ANY, &dwType, (PVOID)&buff, &size);

Below is a picture that I've added the registry value "test" to the Run key (mentioned above).

The error code I get is 2 which represents an invalid file.

It should be mentioned that the local host is running Windows 10 Pro x64.

What could be the source of this confusion?

enter image description here

Modified code:

I still get the error code 2 after using the KEY_WOW64_64KEY flag.

RegCreateKeyEx(
        HKEY_LOCAL_MACHINE,
        TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"),
        NULL,
        NULL,
        REG_OPTION_NON_VOLATILE,
        KEY_ALL_ACCESS | KEY_WOW64_64KEY,
        NULL,
        &hKey,
        &dwStatus) 

long result = RegGetValue(hKey, NULL, TEXT("test"), RRF_RT_ANY, &dwType, (PVOID)&buff, &size);

Solution

  • Problem

    You are most probably trying to access the 64-bit registry view from a 32-bit application.

    By default, a 32-bit application running on WOW64 accesses the 32-bit registry view and a 64-bit application accesses the 64-bit registry view. The following flags enable 32-bit applications to access redirected keys in the 64-bit registry view and 64-bit applications to access redirected keys in the 32-bit registry view. These flags have no effect on shared registry keys.

    Solution

    You can rebuild your application in x64 mode or you can specify which view of the registry you require.

    HKEY key;
    RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"), 0, KEY_ALL_ACCESS | KEY_WOW64_64KEY, &key);
    long result = RegGetValue(key, nullptr, TEXT("test"), RRF_RT_ANY, &dwType, (PVOID)&buff, &size);
    

    For more info: Accessing an Alternate Registry View