windows下实现程序的开机自启动和取消开机自启动
程序员文章站
2022-05-09 08:09:05
...
#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);
}
}
推荐阅读