This codes purpose is to add or edit the value of KeyboardDelay REG_SZ. What I can do is make its value 0 but when I try making it 31, it fails and a weird “box” comes as KeyboardDelays data value instead of the number 31. What am I doing wrong with this since it wont add 31 but it will do 0?
HKEY key;
if (RegOpenKey(HKEY_CURRENT_USER, TEXT("Control Panel\\Keyboard"), &key) != ERROR_SUCCESS)
{
cout << "Unable to open registry key";
}
if (RegSetValueEx(key, TEXT("KeyboardDelay"), 0, REG_SZ, (LPBYTE)"31", strlen("31")*sizeof(char)) != ERROR_SUCCESS)
{
RegCloseKey(key);
cout <<"Unable to set registry value value_name";
}
else
{
cout << "KeyboardDelay was set" << endl;
}
RegSetValueEx is defined in winreg.h as follows:
this means that when UNICODE is defined then RegSetValueExW will be used. The last letter ‘W’ means that it accepts wide character strings (wchar_t*), ‘A’ means it accept multibyte character strings. So if you know you are compiling with UNICODE enabled (project properties -> Configuration -> Character Set -> Use Unicode Character Set), you should provide wide character string literals. The easiest way under windows is to use macros:
or my favorite:
those two macros will result into “31” under non UNICODE compilation, and into L”31″ under UNICODE compilation.
also you should use proper string functions, to get length use wcslen for UNICODE and strlen for multibyte character set. You can use _t* macros that check character set for you and use _tcslen() to get length.
Actually you should always use UNICODE when creating new projects.
to fix your code use :
sizeof(TCHAR) is used here because when UNICODE is defined then single character is two bytes length, and RegSetValueEx requires number of bytes and not number of characters.