我是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)
笔记:
std::wstring.这使得字符串处理变得简单.RegQueryValueEx返回REG_SZ以null结尾的数据.此代码通过截断超出第一个空字符来处理该问题.如果返回的值不是以null结尾,则不会发生截断,但值仍然可以正常.MessageBox.像这样:MessageBox(0, value.c_str(), L"Caption", MB_OK)| 归档时间: |
|
| 查看次数: |
22384 次 |
| 最近记录: |