I want to add a value to the Run key of the Windows Registry in order for my program to run at startup. I have written the following code. It compiles and links successfully. And when I debug the project, it doesn't give any errors. But, my key doesn't get added to the Registry.
int wmain(int argc, wchar_t* argv[])
{
HKEY key_handle;
std::wstring start_name = L"MyApplication";
std::wstring exe_path = L"C:\\Users\\user\\AppData\\Roaming\\Microsoft\\Windows\\MyApp.exe";
LONG result = RegOpenKeyEx(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_WRITE, &key_handle);
if (ERROR_SUCCESS == result)
{
result = RegSetValueEx(key_handle, start_name.c_str(),
0,
REG_SZ,
(unsigned char*)exe_path.c_str(),
exe_path.length() * sizeof(wchar_t));
if (result != ERROR_SUCCESS)
{
printf("Error setting key %d\n", GetLastError());
}
}
else
{
printf("Error opening key %d\n", GetLastError());
}
RegCloseKey(key_handle);
return 0;
}