windows c++ RegSetValueEx 在注册表中只设置一个字符值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4484962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 15:49:30  来源:igfitidea点击:

c++ RegSetValueEx sets only one char value in registry

c++windowswinapiregistry

提问by Tom

I'm casting (char * ) on data and i'm getting only one char value in the registry. if i don't use the casting msvc 2010 tells me that the argument type LPCTSTR is incompatible with const char *.

我正在对数据进行 (char * ) 转换,但我在注册表中只获得了一个 char 值。如果我不使用强制转换 msvc 2010 会告诉我参数类型 LPCTSTR 与 const char * 不兼容。

can someone help me?

有人能帮我吗?

HKEY hKey;
LPCTSTR sk = TEXT("SOFTWARE\Microsoft\Windows\CurrentVersion\Run");

LONG openRes = RegOpenKeyEx(HKEY_CURRENT_USER, sk, 0, KEY_ALL_ACCESS , &hKey);

if (openRes==ERROR_SUCCESS) {
    printf("Success opening key.");
} else {
    printf("Error opening key.");
}

LPCTSTR value = TEXT("SomeKey");
LPCTSTR data = L"TestData
LPCTSTR value = TEXT("SomeKey");
LPCTSTR data = TEXT("TestData");

LONG setRes = RegSetValueEx(hKey, value, 0, REG_SZ, (LPBYTE)data, _tcslen(data) * sizeof(TCHAR));
"; LONG setRes = RegSetValueEx (hKey, value, 0, REG_SZ, (LPBYTE)data, strlen(data)+1); if (setRes == ERROR_SUCCESS) { printf("Success writing to Registry."); } else { printf("Error writing to Registry."); } cout << setRes << endl; LONG closeOut = RegCloseKey(hKey); if (closeOut == ERROR_SUCCESS) { printf("Success closing key."); } else { printf("Error closing key."); }

回答by Joel Rondeau

strlen(data)is probably returning a value of 1, as strlen expects a char* and L"TestData\0"is wide. Use TEXT("TestData\0")and call _tcslen(data).
Note that RegSetValueExexpects the sizeof the data, so use _tcslen(data) * sizeof(TCHAR)

strlen(data)可能返回值 1,因为 strlen 需要一个 char* 并且L"TestData\0"是宽的。使用TEXT("TestData\0")和调用_tcslen(data)
请注意,RegSetValueEx期望数据的大小,因此请使用_tcslen(data) * sizeof(TCHAR)

回答by zenzelezz

Where are you casting data?

你在哪里投射数据?

Either way, it looks like you may be working with wide characters, but you seem to be using "plain old" strlen - instead of wcslen or some other function intended to work with wide-character strings.

无论哪种方式,看起来您可能正在使用宽字符,但您似乎正在使用“普通旧” strlen - 而不是 wcslen 或其他一些旨在处理宽字符串的函数。

回答by vnduan

replace the L"TestData"by _T("TestData");and strlen(data)+1by tcslen(data) * sizeof(TCHAR));

替换L"TestData"by_T("TestData");strlen(data)+1bytcslen(data) * sizeof(TCHAR));

so your code looks like this :

所以你的代码看起来像这样:

##代码##