如何读取Registry的键值并使用MessageBox()将其打印到屏幕上

Lut*_*her 8 c++ winapi

我是C++和WinCe开发的新手.

我想从注册表中读取一个字符串并显示MessageBox().我尝试了以下内容.

HKEY key;
if (::RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("System\\CurrentControlSet\\GPS Intermediate Driver\\Drivers\\SiRFStar3HW"), 0, KEY_READ, &key) != ERROR_SUCCESS)
{
    MessageBox(NULL,L"Can't open the registry!",L"Error",MB_OK);
}
char value[5];
DWORD value_length=5;
DWORD type=REG_SZ;
RegQueryValueEx(key,(LPCTSTR)"Baud", NULL, &type, (LPBYTE)&value, &value_length);
wchar_t buffer[5];
_stprintf(buffer, _T("%i"), value);

::MessageBox(NULL,buffer,L"Value:",MB_OK);

::RegCloseKey(key);
Run Code Online (Sandbox Code Playgroud)

所以我知道这里有些不对劲,但我怎么解决?

Dav*_*nan 19

导航Win32 API可能是一件棘手的事情.注册表API是一些更复杂的.这是一个简短的程序,用于演示如何读取注册表字符串.

#include <Windows.h>
#include <iostream>
#include <string>

using namespace std;

wstring ReadRegValue(HKEY root, wstring key, wstring name)
{
    HKEY hKey;
    if (RegOpenKeyEx(root, key.c_str(), 0, KEY_READ, &hKey) != ERROR_SUCCESS)
        throw "Could not open registry key";

    DWORD type;
    DWORD cbData;
    if (RegQueryValueEx(hKey, name.c_str(), NULL, &type, NULL, &cbData) != ERROR_SUCCESS)
    {
        RegCloseKey(hKey);
        throw "Could not read registry value";
    }

    if (type != REG_SZ)
    {
        RegCloseKey(hKey);
        throw "Incorrect registry value type";
    }

    wstring value(cbData/sizeof(wchar_t), L'\0');
    if (RegQueryValueEx(hKey, name.c_str(), NULL, NULL, reinterpret_cast<LPBYTE>(&value[0]), &cbData) != ERROR_SUCCESS)
    {
        RegCloseKey(hKey);
        throw "Could not read registry value";
    }

    RegCloseKey(hKey);

    size_t firstNull = value.find_first_of(L'\0');
    if (firstNull != string::npos)
        value.resize(firstNull);

    return value;
}

int wmain(int argc, wchar_t* argv[])
{
    wcout << ReadRegValue(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion", L"CommonFilesDir");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  1. 我没有CE所以这是一个简单的Win32应用程序,为Unicode编译.我采取了这条路线,因为CE不做ANSI字符.
  2. 我利用了许多C++功能.最重要的std::wstring.这使得字符串处理变得简单.
  3. 我已经使用异常来处理错误.您可以用其他机制替换它,但它有助于我在后台保持错误处理问题.
  4. 使用异常会使关闭注册表项略显混乱.更好的解决方案是使用RAII类来包装注册表项的生命周期.为简单起见,我省略了这一点,但在生产代码中,您需要采取额外的步骤.
  5. 通常,RegQueryValueEx返回REG_SZ以null结尾的数据.此代码通过截断超出第一个空字符来处理该问题.如果返回的值不是以null结尾,则不会发生截断,但值仍然可以正常.
  6. 我刚刚打印到我的控制台,但是打电话对你来说是微不足道的MessageBox.像这样:MessageBox(0, value.c_str(), L"Caption", MB_OK)