gpt4 book ai didi

c++ - 如何读取注册表的键值并使用 MessageBox() 将其打印到屏幕上

转载 作者:可可西里 更新时间:2023-11-01 17:09:10 25 4
gpt4 key购买 nike

我是 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);

所以我知道这里有问题,但我该如何解决?

最佳答案

浏览 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;
}

注意事项:

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

关于c++ - 如何读取注册表的键值并使用 MessageBox() 将其打印到屏幕上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10675705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com