Search code examples
c++registrywinreg

I am getting error 2 in my winreg function


My code:

HKEY hKey;
char *path = "SYSTEM\\CurrentControlSet\\Control\\IDConfigDB\\Hardware Profiles\\0001\\HwProfileGuid";
LONG result = RegOpenKeyExA(HKEY_LOCAL_MACHINE, path, 0, KEY_ALL_ACCESS, &hKey);
QString q = QString::number(result);

if (result == ERROR_SUCCESS) {
    QMessageBox messageBox1;
    messageBox1.critical(0,"Error", "Success");
    messageBox1.setFixedSize(500,200);
} else {
    QMessageBox messageBox2;
    messageBox2.critical(0,"Error", q);
    messageBox2.setFixedSize(500,200);
}

The error I am getting:

image

Where the key is in my Registry:

image

I think the problem is related to the way I put the info in the path variable, but I am not sure.


Solution

  • You have HwProfileGuid in the wrong place.

    HwProfileGuid is a value inside of the 0001 key, but you are trying to open HwProfileGuid as a sub-key of 0001 instead, which is why you are getting error 2 (ERROR_FILE_NOT_FOUND), because there is no sub-key named HwProfileGuid.

    Also, KEY_ALL_ACCESS is too many rights to request just to read a value from a key. Use KEY_QUERY_VALUE instead. Don't request more rights than you actually need.

    Try this:

    const char *path = "SYSTEM\\CurrentControlSet\\Control\\IDConfigDB\\Hardware Profiles\\0001";
    const char *valueName = "HwProfileGuid";
    char guid[40] = {0};
    
    HKEY hKey;
    LONG result = RegOpenKeyExA(HKEY_LOCAL_MACHINE, path, 0, KEY_QUERY_VALUE, &hKey);
    if (result == ERROR_SUCCESS) {
        DWORD size = sizeof(guid);
        result = RegQueryValueExA(hKey, valueName, NULL, NULL, reinterpret_cast<LPBYTE>(guid), &size);
        RegCloseKey(hKey);
    }
    
    QMessageBox messageBox;
    if (result == ERROR_SUCCESS) {
        messageBox.critical(0, "Success", guid);
    } else {
        messageBox.critical(0, "Error", QString::number(result));
    }
    messageBox.setFixedSize(500, 200);
    

    Alternatively, you can use RegGetValueA() instead of using RegOpenKeyExA()+RegQueryValueExA():

    const char *path = "SYSTEM\\CurrentControlSet\\Control\\IDConfigDB\\Hardware Profiles\\0001";
    const char *valueName = "HwProfileGuid";
    char guid[40] = {0};
    DWORD size = sizeof(guid);
    QMessageBox messageBox;
    
    LSTATUS result = RegGetValueA(HKEY_LOCAL_MACHINE, path, valueName, RRF_RT_REG_SZ, NULL, guid, &size);
    if (result == ERROR_SUCCESS) {
        messageBox.critical(0, "Success", guid);
    } else {
        messageBox.critical(0, "Error", QString::number(result));
    }
    messageBox.setFixedSize(500, 200);