Rehtt's Blog - 个人学习分享 - C
type: channel
link: https://rehtt.com/index.php/tag/C/
items: 【C++】修改注册表管理开机启动项

【C++】修改注册表管理开机启动项
type: item
date: 2018-10-16T00:00:00+00:00
description: // 程序开机自动启动 void autostart() { HKEY hKey; QString strRegPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"; //1、找到系统的启动项 if (RegOpenKeyEx(HKEY_CURRENT_USER, strRegPath.toStdString().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); ///"GISRestart"是应用程序名字 //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 { MessageBox(NULL, "设置失败", "error", 0); } } // 取消开机自动启动 void cancelAutoStart() { HKEY hKey; const char* strRegPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"; //1、找到系统的启动项 if (RegOpenKeyEx(HKEY_CURRENT_USER, strRegPath, 0, KEY_ALL_ACCESS, &hKey) == ERROR_SUCCESS) { //2、删除值 RegDeleteValue(hKey, "GISRestart"); //3、关闭注册表 RegCloseKey(hKey); } }