writing autorun path to registry not working

Hi,

I'm trying to make my exe autorun at startup, so I created this function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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
				   &reg_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?

Best regards,
Yours3!f
Last edited on
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).
Last edited on
Does it make sense to write a different registry value if autorun is off? Wouldn't the correct thing be to remove the entry you added?
thanks webJose it solved the problem :)

@kbw umm I'm not at that point right now, I'll deal with that later :)
Topic archived. No new replies allowed.