0%

C++读写注册表

  1. 工具函数
  2. 示例代码

工具函数

C/C++ 实现读写注册表 - lyshark - 博客园 (cnblogs.com)

RegCreateKeyExA 函数 (winreg.h) - Win32 apps | Microsoft Learn

RegOpenKeyExA:打开注册表下的某个路径,获取句柄

RegQueryValueExA:读取路径下某个键的值

RegCreateKeyExA:创建注册表下某个路径,并获取句柄,支持嵌套创建(比如HKEY_CLASSES_ROOT\A\B\C这种直接创建,不需要一层一层判断存在再创建)

RegSetValueExA:设置值

RegCloseKey:关闭已打开的句柄

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <windows.h>
#include <string>

static std::string ReadRegKeyValue(const HKEY hKey,
const std::string& fullPath,
const std::string& keyName)
{
std::string logTag = "[" + fullPath + "][" + keyName + "]";

HKEY hKey_return = NULL;
if (ERROR_SUCCESS != RegOpenKeyExA(hKey,
fullPath.c_str(),
0,
KEY_READ,
&hKey_return))
{
throw std::runtime_error(logTag + "键打开失败");
}

char keyValue[256] = { 0 };
DWORD keySzType = 0;
DWORD keySize = 256;
if (ERROR_SUCCESS != RegQueryValueExA(hKey_return,
keyName.c_str(),
0,
&keySzType,
(LPBYTE)&keyValue,
&keySize))
{
throw std::runtime_error(logTag + "值读取失败");
}

if (ERROR_SUCCESS != RegCloseKey(hKey_return))
{
throw std::runtime_error(logTag + "键关闭失败");
}

return keyValue;
}

static void WriteRegKeyStringValue(const HKEY hKey,
const std::string& fullPath,
const std::string& keyName,
const std::string& value)
{
std::string logTag = "[" + fullPath + "][" + keyName + "][" + value + "]";

HKEY hKey_return = NULL;
DWORD dwCreateKeyResult = NULL;
if (ERROR_SUCCESS != RegCreateKeyExA(hKey,
fullPath.c_str(),
0,
NULL,
REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS,
NULL,
&hKey_return,
&dwCreateKeyResult))
{
throw std::runtime_error(logTag + "键创建失败: " + std::to_string(dwCreateKeyResult));
}

if (ERROR_SUCCESS != RegSetValueExA(hKey_return,
keyName.c_str(),
0,
REG_SZ,
(LPBYTE)value.c_str(),
(DWORD)value.size()))
{
throw std::runtime_error(logTag + "值设置失败");
}

if (ERROR_SUCCESS != RegCloseKey(hKey_return))
{
throw std::runtime_error(logTag + "键关闭失败");
}
}

示例代码

读写注册表,需要管理员权限,在“属性-链接器-清单文件-UAC执行级别”这边,改成requireAdministrator

image-20240711165330045

执行以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

int main()
{
try
{
std::string fullPath = "Smart.UAV\\";
std::string keyName = "URL Protocol";
std::string value = "123456";

WriteRegKeyStringValue(HKEY_CLASSES_ROOT, fullPath, keyName, value);

std::cout << ReadRegKeyValue(HKEY_CLASSES_ROOT, fullPath, keyName) << std::endl;
return 0;
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
return -1;
}
}

注册表里的结果:

image-20240711165859497