设置开机启动

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);
    //64位系统会自动切换到“HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run”
    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);
}

猜你喜欢

转载自blog.csdn.net/jin_huan11/article/details/58662691