First, demand
Paper implements MFC program at startup function.
Second, the design
At startup can be achieved through the registry. In Run
the node, a new field, including the program name, the full path. If you want to cancel the automatic start, the field can be deleted.
Third, coding
code show as below:
int SetAutorun(BOOL nEnable)
{
// 获取程序路径
CString sPath;
GetModuleFileName(NULL, sPath.GetBufferSetLength(MAX_PATH + 1), MAX_PATH);
char lpPath[MAX_PATH] = {0};
strcpy_s(lpPath, (const char*)sPath.GetBuffer());
HKEY hkey;
DWORD dwLen = MAX_PATH;
int ret = -1;
// 注意,不能使用HKEY_LOCAL_MACHINE,权限不够
ret = RegOpenKeyEx(HKEY_CURRENT_USER,
_T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\"),
0, KEY_WRITE, &hkey);
if (ret != ERROR_SUCCESS)
{
return -1;
}
if (nEnable)
{
RegSetValueEx(hkey, _T("MyTest"), 0, REG_SZ, (CONST BYTE *)sPath.GetBuffer(), dwLen);
}
else
{
RegDeleteValue(hkey, _T("MyTest"));
}
RegCloseKey(hkey);
return 0;
}