RegCreateKeyEx成功,但未添加任何密钥



我正试图在Windows上进行C++编程以实现反向工程,但我一直在尝试使用Windows注册表项。函数RegCreateKey和RegSetValueEx返回ERROR_SUCCESS,但在检查注册表时缺少该项。

这是代码:

void AddRunKey() {
wchar_t subkey[512];
wchar_t cmd[512];
wcscpy_s(subkey, L"Test");
wcscpy_s(cmd, L"%windir%system32cmd.exe");
HKEY runKey;
long res;
res = RegCreateKeyEx(HKEY_CURRENT_USER, L"SOFTWARE\Microsoft\Windows\CurentVersion\Run", 0, NULL, 0, KEY_ALL_ACCESS, NULL, &runKey, NULL);
if (res != ERROR_SUCCESS) {
std::cout << "failn";
}

res = RegSetValueEx(runKey, subkey, 0, REG_EXPAND_SZ, (BYTE*)cmd, wcslen(cmd) + 1);
if (res != ERROR_SUCCESS) {
std::cout << "failn";
}
RegCloseKey(runKey);
}

int _tmain() {
AddRunKey();

}

我在Visual Studio上编译了它,发布模式,64位,在Windows 10-64位虚拟机上。运行代码时不会返回任何错误。

打开Windows注册表编辑器时,在HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run下,找不到密钥

是什么导致了这种行为?我该怎么修?

EDIT(更新密钥路径(:RegCloseKey返回0

我在您的代码中看到了几个错误。

您需要对文件路径中的字符进行转义。

您在密钥路径中拼错了CurentVersion。它需要改为CurrentVersion

无论RegCreateKeyEx()成功还是失败,您都在无条件地调用RegSetValueEx()RegCloseKey()

您需要在RegSetValueEx()的最后一个参数中以字节而非字符指定值大小。

试试这个:

void AddRunKey() {
wchar_t subkey[512];
wchar_t cmd[512];
wcscpy_s(subkey, L"Test");
wcscpy_s(cmd, L"%windir%\system32\cmd.exe");
HKEY runKey;
long res = RegCreateKeyEx(HKEY_CURRENT_USER, L"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", 0, NULL, 0, KEY_SET_VALUE, NULL, &runKey, NULL);
if (res != ERROR_SUCCESS) {
std::cout << "failn";
}
else
{
res = RegSetValueEx(runKey, subkey, 0, REG_EXPAND_SZ, (BYTE*)cmd, (wcslen(cmd) + 1) * sizeof(cmd[0]));
if (res != ERROR_SUCCESS) {
std::cout << "failn";
}
RegCloseKey(runKey);
}
}

int _tmain() {
AddRunKey();
}

相关内容

最新更新