Search code examples
c++registryregedit

My winreg function is not being recognized


The error:

error: no matching function for call to 'RegCreateKeyExW'

What I am including:

#include <iostream>
#include <Windows.h>
#include <stdio.h>
#include <string>
#include <winreg.h>

My code:

        HKEY hKey;
        LONG result = 0;
        char *path = "SYSTEM\\CurrentControlSet\\Control\\IDConfigDB\\Hardware Profiles\\0001";

        if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, path, 0, NULL,
                REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, NULL) == ERROR_SUCCESS) {
            printf("2. success \n");
        } else {
            printf("fail\n");
        }

I have tried everything but this error won't vanish, I would aprecciate if someone could help me!


Solution

  • You are calling the TCHAR version of RegCreateKeyEx(). It is clear from the error message that RegCreateKeyEx() is resolving to the Unicode version, RegCreateKeyExW() (because UNICODE is defined in your build config). That version takes in a wide wchar_t string as input, but you are passing in a narrow char string instead.

    You can either:

    1. use a TCHAR string, to match the TCHAR function your code is calling:
    const TCHAR* path = TEXT("SYSTEM\\CurrentControlSet\\Control\\IDConfigDB\\Hardware Profiles\\0001");
    
    1. use a Unicode string, to match the Unicode function actually being called at runtime:
    const wchar_t *path = L"SYSTEM\\CurrentControlSet\\Control\\IDConfigDB\\Hardware Profiles\\0001";
    
    1. use the ANSI version of the function, RegCreateKeyExA(), to match your original string:
    if (RegCreateKeyExA(...) == ERROR_SUCCESS) {