windows 从 RegQueryValueEx 获取正确的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4931774/
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 16:08:17  来源:igfitidea点击:

Getting a proper value from RegQueryValueEx

c++windowsregistry

提问by cftmon

I am trying to extract a value from the windows registry of type REG_SZ, using RegQueryValueEx, I got the value except it was riddled with strange "\000" before each letter.To show you what I mean here are some images:

我正在尝试从类型为 的 Windows 注册表中提取一个值REG_SZ,使用RegQueryValueEx,我得到了该值,只是在每个字母前都充满了奇怪的“\000”。为了向您展示我的意思,这里有一些图像:

Value I want(It is a device name of a wireless adapter) enter image description here

我想要的值(它是无线适配器的设备名称) enter image description here

Value I got:

我得到的价值:

enter image description here

enter image description here

here is the code:

这是代码:

    HKEY hlistkey = NULL;
    HKEY hkey = NULL;

    int dwIndex=0;

    string devName = returndevName(); //return current selected device name using iphlpapi.h  
    WCHAR KeyNameBuf[512];
    DWORD keyNameSizBuf = 512;

    char buffer[512];


    RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002bE10318}") ,0,KEY_READ, &hlistkey );
    if(!hlistkey)
    {
        cout << "failed" << endl;
    }
    while(RegEnumKeyEx(hlistkey,dwIndex++,KeyNameBuf,&keyNameSizBuf,0,NULL,NULL,NULL) == ERROR_SUCCESS )
    {

        RegOpenKeyEx(hlistkey, KeyNameBuf, 0, KEY_READ | KEY_SET_VALUE, &hkey);
        if(hkey)
        {
            keyNameSizBuf = 512;
            if(RegQueryValueEx(hkey,TEXT("NetCfgInstanceId"), 0,NULL,(LPBYTE)buffer,&keyNameSizBuf ) == ERROR_SUCCESS )
            {
                if(strcmp(buffer,devName.c_str() ) ==0)
                {
                    //set value here
                }
            }
            RegCloseKey(hkey);
        }        
    }
}

comparing bufferand devNamewould not be the same because of the extra null characters .If I cast buffer to a string I simply got a "{" which is the first value.I need to get the value of the devenamein the registry before I can change the "NetworkAddress" in the registry.

比较buffer并且devName由于额外的空字符而不会相同。如果我将缓冲区转换为字符串,我只会得到一个“{”,这是第一个值。devename我需要先获取注册表中的值,然后才能更改注册表中的“网络地址”。

回答by Loghorn

Since you are using WCHAR, I assume you are compiling with Unicode support. If this is true, then also the bufferneeds to be WCHAR.

由于您使用的是WCHAR,我假设您正在使用 Unicode 支持进行编译。如果这是真的,那么也buffer需要是WCHAR