简体   繁体   English

读取注册表项时如何解决问题?

[英]How can I solve the problem when reading a registry entry?

i want to get the value from an registry entry.我想从注册表项中获取值。 Here is my code:这是我的代码:

#include <atlbase.h>
#include <atlstr.h>
#include <iostream>
#define BUFFER 8192
int main()
{
    char value[255];
    DWORD BufferSize = BUFFER;
    RegGetValue(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ActiveComputerName", L"ComputerName", RRF_RT_REG_SZ, NULL, (PVOID)&value, &BufferSize);
    std::cout << value << std::endl;
}

My Computer name is: DESKTOP-IGW3F .我的电脑名称是: DESKTOP-IGW3F But if i run my program my output is: D但是如果我运行我的程序,我的输出是: D

I have no idea how to fix it...i hope you can help me.我不知道如何解决它......我希望你能帮助我。

The Win32 function RegGetValue() does not exist. Win32 函数RegGetValue()不存在。 It is only a preprocessor macro that will resolve to either RegGetValueA() or RegGetValueW() depending on your project settings.它只是一个预处理器宏,可以根据您的项目设置解析为RegGetValueA()RegGetValueW() In your case, the macro resolves to RegGetValueW() , therefore it treats the registry value as a Unicode string (2 bytes per character).在您的情况下,宏解析为RegGetValueW() ,因此它将注册表值视为 Unicode 字符串(每个字符 2 个字节)。 But you are using a char (1 byte per character) buffer to receive the Unicode data.但是您正在使用char (每个字符 1 个字节)缓冲区来接收 Unicode 数据。

To make your code work, you need to either explicitly call RegGetValueA() instead, or change your buffer type from char to wchar_t .要使您的代码正常工作,您需要改为显式调用RegGetValueA() ,或者将缓冲区类型从char更改为wchar_t Either way, you should also check the return value of the function.无论哪种方式,您还应该检查函数的返回值。

A working example could look like this:一个工作示例可能如下所示:

#include <windows.h>
#include <iostream>

int main() 
{
    WCHAR value[255];
    DWORD bufferSize = 255 * sizeof(WCHAR);

    if (!RegGetValueW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ActiveComputerName", L"ComputerName", RRF_RT_REG_SZ, NULL, value, &bufferSize))
    {
        std::wcout << value << std::endl;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM