c++开机自起动代码

· · 个人记录

#include <windows.h>
   #include <iostream>

   // 将程序添加到注册表实现开机自启动
   bool AddToStartup(const char* appName, const char* appPath) {
    HKEY hKey;
    DWORD retCode;

    // 打开注册表项
    retCode = RegOpenKeyExA(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_WRITE, &hKey);
    if (retCode != ERROR_SUCCESS) {
        std::cerr << "无法打开注册表项" << std::endl;
        return false;
    }

    // 设置程序路径
    retCode = RegSetValueExA(hKey, appName, 0, REG_SZ, reinterpret_cast<const BYTE*>(appPath), strlen(appPath) + 1);
    if (retCode != ERROR_SUCCESS) {
        std::cerr << "无法设置注册表项" << std::endl;
        RegCloseKey(hKey);
        return false;
    }

    RegCloseKey(hKey);
    return true;
}

// 获取程序自身的绝对路径
std::string GetExecutablePath() {
    char buffer[MAX_PATH];
    GetModuleFileNameA(NULL, buffer, MAX_PATH);
    return std::string(buffer);
}

int main() {
    const char* appName = "MyApp"; // 自启动项名称

    // 获取程序自身的绝对路径
    std::string appPath = GetExecutablePath();

    if (AddToStartup(appName, appPath.c_str())) {
        std::cout << "程序已添加到开机自启动" << std::endl;
    } else {
        std::cerr << "添加到开机自启动失败" << std::endl;
    }

    return 0;
}