RegSetValueEx and CHAR

RegSetValueEx and CHAR

本文关键字:CHAR and RegSetValueEx      更新时间:2023-10-16

考虑以下代码

addHash("hash");
bool addHash(char* hash) {
    HKEY hKey = 0;
    int code = RegOpenKey(HKEY_CURRENT_USER, subkey, &hKey);
    const int length = strlen(hash)+1;
    WCHAR whash[100];
    MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, hash, strlen(hash), whash, 100);
    LONG setRes = RegSetValueEx(hKey, L"hash", 0, REG_SZ, (LPBYTE)whash, strlen(hash)+1);
    return true;
}

在代码被编译和执行之后,"ha"被放入注册表。有人能告诉我问题出在哪里吗?

提前谢谢!

最后一个参数是倒数第二个参数所指向的字节数,而不是字符数。

因此,whash的前五个字节(strlen(hash) + 1)将存储在注册表中。更改为:

LONG setRes = RegSetValueEx(hKey,
                            L"hash",
                            0,
                            REG_SZ,
                            (LPBYTE)whash,
                            (wcslen(whash) + 1) * sizeof(WCHAR));

您可能还需要初始化whash(我不认为MultiByteToWideChar()会为您添加空终止符):

WCHAR whash[100] = { 0 };

我想这就是你想要做的:

#include <tchar.h>
#include <Windows.h>
using namespace std;
bool addHash(wstring hash) {
    const wchar_t* wHash = hash.c_str();
    LONG ret = RegSetKeyValue(HKEY_CURRENT_USER, _T("Software\aa\test"), _T("hash"), REG_SZ, wHash, hash.length() * sizeof(wchar_t));
    return (ret == ERROR_SUCCESS);
}
int main()
{
    addHash(_T("A42B2094EDC43"));
    return 0;
}

希望这能有所帮助;)