开发者

How do I store value to string with RegOpenKeyEx?

I need to grab the path from the registry. The following code works except for the last part where I'm storing the path to the string. Running the debugger in Visual Studio 2008 the char array has the path, but every other character is a zero. This results in the string only being assigned the first letter. I've tried changing char res[1024] to char *res = new char[1024] and this just makes it store the first letter in the char array instead of the string. The rest of the program needs the path as a string datatype so it can't stay as a char array. What am I missing here?

unsigned long type=REG_SZ, size=1024;
str开发者_开发问答ing path;
char res[1024];
HKEY key;

if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Classes\\dsn\\shell\\open\\command"), NULL, KEY_READ, &key)==ERROR_SUCCESS){

    RegQueryValueEx(key,
    NULL,// YOUR value
    NULL,
    &type,
    (LPBYTE)res,
    &size);
    RegCloseKey(key);

    path = string(res);
}


You're getting back a Unicode string, but assigning it to a char-based string.

You could switch path's class to being a 'tstring' or 'wstring', or use RegQueryValueExA (A for ASCII).


You are compiling in Unicode. Go to Project Settings>Configuration Properties>General and change "Character Set" to "Not Set", and rebuild your project.

RegOpenKey is actually a macro defined in the WINAPI headers. If Unicode is enabled, it resolves to RegOpenKeyW, if not then it resolves to RegOpenKeyA. If you want to continue to compile under unicode, then you can just call RetgOpenKeyA directly instead of using the macro.

Otherwise, you'll need to deal with Unicode strings which, if needed, we can help you with also.


For C++, you may prefer to access the Registry using the ATL helper class CRegKey. The method for storing string values is QueryStringValue. There are other (somewhat) typesafe methods for retrieving and setting different registry value types.

It's not the best C++ interface (eg. no std::string support) but a little smoother than native Win32.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜