Qt实现:
bool Util::boot_program(const QString &filePath, bool bEnable)
{
QFileInfo fileInfo(filePath);
if(!fileInfo.exists())
{
printf("set %s run with launch PC failed.", filePath);
return false;
}
QSettings pSettingReg("HKEY_LOCAL_MACHINE", QSettings::NativeFormat);
QString valueStr = "SOFTWARE/Microsoft/Windows/CurrentVersion/Run/" + fileInfo.baseName();
if(bEnable)
{
pSettingReg.setValue(valueStr, "\"" + QDir::toNativeSeparators(fileInfo.absoluteFilePath()) + "\"");
}
else
{
pSettingReg.setValue(valueStr, QString());
}
return true;
}
MFC实现:
void SetAutoRunOnStart(LPCSTR lpszName,BOOL bAddFlag,LPCSTR lpszEXEPath,BOOL bForAllUser)
{
TCHAR *pRegPath = _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
HKEY hKey;
if(bForAllUser)
RegOpenKey(HKEY_LOCAL_MACHINE, pRegPath, &hKey);
else
RegOpenKey(HKEY_CURRENT_USER, pRegPath, &hKey);
CFileStatus st ;
CString strEXEFile(lpszEXEPath);
if(!CFile::GetStatus(strEXEFile,st))
strEXEFile=__argv[0];
CString strName(lpszName) ;
if(strName.IsEmpty())
{
int nFind = strEXEFile.ReverseFind(
strName = strEXEFile.Mid(nFind+1) ;
int nLen = strName.GetLength() ;
strName = strName.Left(nLen-4) ;
}
LPCSTR pName = (LPCSTR)strName ;
if(!bAddFlag)
{
RegDeleteValue(hKey, pName);
}
else
{
strEXEFile += _T(" /OnSysStart");
CONST BYTE *lpData = (BYTE *)(LPCSTR)strEXEFile;
DWORD dwLen = strEXEFile.GetLength();
RegSetValueEx(hKey, pName, 0, REG_SZ, lpData, dwLen);
}
RegCloseKey(hKey);
}