实例代码如下:
wchar_t szValue[] = L"liuanValue123";
DWORD dwType = REG_SZ;
DWORD dwByteLen = (wcslen(szValue) )*sizeof(wchar_t) ;
SHSetValueW(HKEY_CLASSES_ROOT, L"liuan",NULL, dwType, szValue, dwByteLen);
wchar_t Value[MAX_PATH] = {0};
SHGetValueW(HKEY_CLASSES_ROOT, L"liuan", NULL, &dwType, Value, &dwByteLen);
经调试得出,读取数据后value的值认为0, 如果value没有被初始话的时候,则乱码,上述代码第三行换为
DWORD dwByteLen = (wcslen(szValue) + 1 )*sizeof(wchar_t) 成功读取。
为了验证在多字节环境下,以上代码能否正常工作,改为:
TCHAR szValue[] = _T("liuanValue123");
DWORD dwType = REG_SZ;
DWORD dwByteLen = (_tcslen(szValue))*sizeof(TCHAR) ;
TCHAR szSubKey[] =_T("liuan");
TCHAR value[MAX_PATH] = {0};
SHSetValue(HKEY_CLASSES_ROOT, szSubKey,NULL, dwType, szValue, dwByteLen);
SHGetValue(HKEY_CLASSES_ROOT, szSubKey, NULL, &dwType, value, &dwByteLen);
调试得出结论, 上述代码仍然不能读出正确的字符串,加一之后就能正常工作。
在来看msdn上面的说明:
msdn 2005:SHSetValue最后一个参数:
cbData
Length, in bytes, of the buffer pointed to by the pvData parameter. If the data is a null-terminated string, this length not includes the terminating null character.