跳到主要内容

Windows 的注册表

注册表是 Windows 操作系统中的一个集中数据库,用于存储系统和应用程序的配置设置。通过注册表,操作系统和应用程序可以存储和读取配置信息,如用户设置、硬件配置、软件安装信息等。

访问注册表可以使用 Windows 提供的一组 API 函数,例如 RegOpenKeyExRegQueryValueExRegSetValueExRegCloseKey 等。

以下是一个使用 C++ 访问注册表的示例,演示如何创建一个注册表项并读取和写入值。

常用函数

创建注册表项

result = RegCreateKeyEx(
HKEY_CURRENT_USER,
subKey,
0,
NULL,
0,
KEY_WRITE | KEY_READ,
NULL,
&hKey,
NULL
);

RegCreateKeyEx 函数用于创建或打开指定的注册表项。在这里,我们创建(或打开)位于 HKEY_CURRENT_USER\SOFTWARE\Example 下的项。

设置注册表项的值

result = RegSetValueEx(
hKey,
valueName,
0,
REG_SZ,
reinterpret_cast<const BYTE*>(data),
strlen(data) + 1
);

RegSetValueEx 函数用于设置指定注册表项的值。在这里,我们设置字符串值 "Hello, Registry!" 到 TestValue 名称下。

读取注册表项的值

result = RegQueryValueEx(
hKey,
valueName,
NULL,
&type,
reinterpret_cast<BYTE*>(buffer),
&bufferSize
);

RegQueryValueEx 函数用于读取指定注册表项的值。在这里,我们读取 TestValue 的值到缓冲区 buffer 中,并验证值的类型是否为字符串 (REG_SZ)。

关闭注册表项

RegCloseKey(hKey);

RegCloseKey 函数用于关闭先前打开的注册表项句柄。

访问注册表示例代码

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

int main() {
HKEY hKey;
const char* subKey = "SOFTWARE\\Example";
LONG result;

// 创建注册表项
result = RegCreateKeyEx(
HKEY_CURRENT_USER,
subKey,
0,
NULL,
0,
KEY_WRITE | KEY_READ,
NULL,
&hKey,
NULL
);

if (result != ERROR_SUCCESS) {
std::cerr << "RegCreateKeyEx failed (error " << result << ")\n";
return 1;
}
std::cout << "Registry key created successfully\n";

// 设置注册表项的值
const char* valueName = "TestValue";
const char* data = "Hello, Registry!";
result = RegSetValueEx(
hKey,
valueName,
0,
REG_SZ,
reinterpret_cast<const BYTE*>(data),
strlen(data) + 1
);

if (result != ERROR_SUCCESS) {
std::cerr << "RegSetValueEx failed (error " << result << ")\n";
RegCloseKey(hKey);
return 1;
}
std::cout << "Registry value set successfully\n";

// 读取注册表项的值
char buffer[256];
DWORD bufferSize = sizeof(buffer);
DWORD type = 0;

result = RegQueryValueEx(
hKey,
valueName,
NULL,
&type,
reinterpret_cast<BYTE*>(buffer),
&bufferSize
);

if (result != ERROR_SUCCESS) {
std::cerr << "RegQueryValueEx failed (error " << result << ")\n";
RegCloseKey(hKey);
return 1;
}

if (type == REG_SZ) {
std::cout << "Registry value: " << buffer << "\n";
} else {
std::cerr << "Unexpected registry value type\n";
}

// 关闭注册表项
RegCloseKey(hKey);
return 0;
}