Я написал две функции install()
и del()
:
#include <windows.h>
#include <Lmcons.h>
#include <iostream>
using namespace std;
void install (char * fileAndPath, char * registryName)
{
const unsigned long size = strlen(fileAndPath);
HKEY software;
HKEY mykey;
long yRes = RegCreateKey(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion", &software);
long nResult = RegCreateKey(software, "Run", &mykey);
long j = RegSetValueEx(mykey, registryName, 0, REG_SZ, (LPBYTE)fileAndPath, size + 1);
if (yRes != ERROR_SUCCESS)
cout << "Error: Could not create registry key yRes " << "\tERROR: " << yRes << endl;
else
cout << "Success: Key created" << endl;
if (nResult != ERROR_SUCCESS)
cout << "Error: Could not create registry key nResult " << "\tERROR: " << nResult << endl;
else
cout << "Success: Key created" << endl;
if (j != ERROR_SUCCESS)
cout << "Error: Could not create registry key j" << "\tERROR: " << j << endl;
else
cout << "Success: Key created" << endl;
RegCloseKey(mykey);
RegCloseKey(software);
}
void del(char * registryName)
{
HKEY software;
HKEY mykey;
RegCreateKey(HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion",&software);
RegCreateKey(software,"Run",&mykey);
RegDeleteValue(mykey, registryName);
RegCloseKey(mykey);
RegCloseKey(software);
}
int main() {
install("C:\\Users\\Dannael\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\test.exe", "TestKey");
}
system("pause");
return 0;
}
Сбой программы после запуска, я не могу найти проблему.
EDIT: я изменил значение размера буфера, как сказал Р. Р., но программа по-прежнему не хочет добавлять ключ в реестр..
EDIT2: Я обновил код.
Вывод:
Success: Key created
Error: Could not create registry key nResult ERROR: 5
Error: Could not create registry key j ERROR: 6
Частично решена:
Изменение значений HKEY_LOCAL_MACHINE на HKEY_CURRENT_USER позволяет записывать ключи в реестре для текущего пользователя
char buffer[60];
strcpy(buffer, fileAndPath);
Вы невольно копируете длинную строку длиной 87 символов в буфер меньшего 60 символов. Следовательно, переполнение буфера.
Как только вы закончите с этим (больший буфер, чтобы сохранить строку, и вариант strcpy_s
функции копирования), вы должны узнать, как:
Проверка результатов:
LONG nResult = RegCreateKey(software, "Run", &mykey);
// If nResult is not ERROR_SUCCESS then hurry up to post this additional
// information on StackOverflow:
// the line exactly, and the value of the nResult variable
... CurrentVersion\\
сейчас?
Вы можете не копировать строку, используя что-то вроде:
void install (const char* fileAndPath, const char* registryName)
{
const unsigned long size = strlen(fileAndPath);
HKEY software;
HKEY mykey;
RegCreateKey(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\", &software);
RegCreateKey(software, "Run", &mykey);
RegSetValueEx(mykey, registryName, 0, REG_SZ, (LPBYTE)fileAndPath, size + 1);
RegCloseKey(mykey);
RegCloseKey(software);
}
RegCreateKeyEx
.