#include <windows.h>
#include <stdio.h>

void AddToAutorun(void)
{
	HKEY hKey;
	char szPath[MAX_PATH];

	GetModuleFileName(NULL, szPath, sizeof(szPath));
	RegCreateKeyEx(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\Run",
			0, NULL, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &hKey, NULL);
	if (hKey)
	{
		RegSetValueEx(hKey, TEXT("MyAutorunZTRSF"), 0, REG_SZ, (LPBYTE)szPath, lstrlen(szPath));
		RegFlushKey(hKey);
		RegCloseKey(hKey);
	}
}

void autorun(void)
{
	TCHAR szPath[MAX_PATH];

	DWORD pathLen = 0;

	// GetModuleFileName returns the number of characters
	// written to the array.
	pathLen = GetModuleFileName(NULL, szPath, MAX_PATH);

	if (pathLen == 0)
		return;

	HKEY newValue;
	if (RegOpenKey(HKEY_LOCAL_MACHINE,
			TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Run"),
			&newValue) != ERROR_SUCCESS)
		{
	    	printf(TEXT("Unable to open registry key; last error = %lu\n"), GetLastError());
	    	return;
	    }
	// Need to pass the length of the path string in bytes,
	// which may not equal the number of characters due to
	// character set.
	DWORD pathLenInBytes = pathLen * sizeof(*szPath);
	if (RegSetValueEx(newValue,
			TEXT("name_me"),
			0,
			REG_SZ,
			(LPBYTE)szPath,
			pathLenInBytes) != ERROR_SUCCESS)
		{
			RegCloseKey(newValue);
			printf(TEXT("Unable to set registry value; last error = %lu\n"), GetLastError());
	    	return;
	    }
	RegCloseKey(newValue);
}

int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	AddToAutorun();
	autorun();
	MessageBox(NULL, TEXT("Hello, World!"), TEXT("Autorun"), MB_OK);
	return 0;
}