void window::set_autorun(BOOL autorun)
{
HKEY reg_key = 0;
LPCTSTR address = _T("Software\\Microsoft\\Windows\\CurrentVersion\\Run");
LONG result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, //hive
address, //address
0,
KEY_ALL_ACCESS, //we want all access
®_key); //handle to the key
if(result != ERROR_SUCCESS)
{
throw std::runtime_error("Couldn't open the registry key!");
}
else
{
DWORD result = 0;
LPCTSTR name = _T("Myautorun");
LPCTSTR value;
if(autorun)
{
TCHAR path[MAX_PATH + 1];
if(!GetModuleFileName(NULL, path, MAX_PATH + 1))
{
throw std::runtime_error("Couldn't get the file path!");
}
value = path;
}
else
{
value = _T("\0");
}
result = RegSetValueEx (reg_key,
name,
0,
REG_SZ,
(LPBYTE)value ,
_tcslen(value) + 1);
if(result != ERROR_SUCCESS)
{
throw std::runtime_error("Couldn't set the registry key!");
}
}
RegCloseKey(reg_key);
}
everything seems to work, except when I open the regedit.exe and do refresh, I can see that the string that is there is truncated, doesn't contain the full path. I checked the "value" variable contains the right string. How can I fix this?
Most likely the problem is that you compiled for Unicode. Of course that is in itself not an error (actually is a very good thing), BUT you did the calculation of bytes incorrectly. Line 40 should be ( _tcslen(value) + 1 ) * sizeof(TCHAR).