windows下實現程序的開機自啓動和取消開機自啓動

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>
#include <winreg.h>
#include <windows.h>
/// 程序開機自動啓動
void autostart()
{
    HKEY hKey;
    QString strRegPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";

    if (RegOpenKeyEx(HKEY_CURRENT_USER,
                     L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",
                     0,
                     KEY_ALL_ACCESS, &hKey) == ERROR_SUCCESS){
        TCHAR strExeFullDir[MAX_PATH];
        GetModuleFileName(NULL, strExeFullDir, MAX_PATH);

        TCHAR strDir[MAX_PATH] = {};
        DWORD nLength = MAX_PATH;
        long result = RegGetValue(hKey, nullptr, L"UBoxOpcstart", RRF_RT_REG_SZ, 0, strDir, &nLength);

        if (result != ERROR_SUCCESS || _tcscmp(strExeFullDir, strDir) != 0)
        {
            RegSetValueEx(hKey, L"UBoxOpcstart", 0, REG_SZ, (LPBYTE)strExeFullDir, (lstrlen(strExeFullDir) + 1)*sizeof(TCHAR));

            RegCloseKey(hKey);
        }
    }else{
        QMessageBox::warning(0, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("\n系統參數錯誤,不能隨系統啓動n"));
    }
}

/// 取消開機自動啓動
void cancelAutoStart()
{
        HKEY hKey;
        QString strRegPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
        if (RegOpenKeyEx(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_ALL_ACCESS, &hKey) == ERROR_SUCCESS){
            RegDeleteValue(hKey, L"UBoxOpcstart");
            RegCloseKey(hKey);
        }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章