向注册表添加新密钥不起作用

时间:2013-12-28 12:41:14

标签: c++ winapi registry

我写了两个函数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;

}

程序在运行后崩溃,我找不到问题。

编辑:我已经改变了缓冲区大小值,正如Roman R.所说,但程序仍然不想将注册表添加到注册表中。

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允许在注册表中为当前用户写入密钥

2 个答案:

答案 0 :(得分:2)

char buffer[60];
strcpy(buffer, fileAndPath);

您不安全地将87个字符的长字符串复制到较小的60个字符的长缓冲区中。因此缓冲区溢出。

完成此操作后(较大的缓冲区用于保存字符串,以及复制功能的strcpy_s变体),您将了解如何:

  • 逐步调试调试器下的代码
  • 检查从API调用获得的结果/状态代码

结果检查:

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

答案 1 :(得分:0)

您可以避免使用以下内容复制字符串:

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);
}
相关问题