C++ 開機自動啟動


針對不需要管理員權限的程序

轉載:https://blog.csdn.net/u010601662/article/details/72851812/

// 程序開機自動啟動
void autostart()
{
    HKEY hKey;
    string strRegPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";

    //1、找到系統的啟動項  
    if (RegOpenKeyEx(HKEY_CURRENT_USER, strRegPath.c_str(), 0, KEY_ALL_ACCESS, &hKey) == ERROR_SUCCESS) ///打開啟動項       
    {
        //2、得到本程序自身的全路徑
        TCHAR strExeFullDir[MAX_PATH];
        GetModuleFileName(NULL, strExeFullDir, MAX_PATH);

        //3、判斷注冊表項是否已經存在
        TCHAR strDir[MAX_PATH] = {};
        DWORD nLength = MAX_PATH;
        long result = RegGetValue(hKey, nullptr, "GISRestart", RRF_RT_REG_SZ, 0, strDir, &nLength);

        //4、已經存在
        if (result != ERROR_SUCCESS || _tcscmp(strExeFullDir, strDir) != 0)
        {
            //5、添加一個子Key,並設置值,"GISRestart"是應用程序名字(不加后綴.exe) 
            RegSetValueEx(hKey, "GISRestart", 0, REG_SZ, (LPBYTE)strExeFullDir, (lstrlen(strExeFullDir) + 1)*sizeof(TCHAR));

            //6、關閉注冊表
            RegCloseKey(hKey);
        }
    }
    else
    {
        QMessageBox::warning(0, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("\n系統參數錯誤,不能隨系統啟動n"));
    }
}

// 取消開機自動啟動
void cancelAutoStart()
{
    HKEY hKey;
    string strRegPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";

    //1、找到系統的啟動項  
    if (RegOpenKeyEx(HKEY_CURRENT_USER, strRegPath.c_str(), 0, KEY_ALL_ACCESS, &hKey) == ERROR_SUCCESS)
    {
        //2、刪除值
        RegDeleteValue(hKey, "GISRestart");

        //3、關閉注冊表
        RegCloseKey(hKey);
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM