定义头文件CYLXQ_Register.h
#pragma once
#define REGISTER_SUBKEY_DEFAULT "Software\\YLXQSoft"
class CYLXQ_Register
{
private:
const char* sub_key;
public:
CYLXQ_Register(const char* subkey);
int SetValue(const char* key, const char* value);
int GetValue(const char* key, char* value);
};
void CYLXQ_RegisterDemo();
定义实现文件CYLXQ_Register.cpp
#include "CYLXQ_Register.h"
#include <Windows.h>
#include <atlbase.h>
#include <iostream>
#include <string>
#include <vector>
// 构造函数,初始化常量
CYLXQ_Register::CYLXQ_Register(const char* subkey):sub_key(subkey){}
int CYLXQ_Register::SetValue(const char* key, const char* value) {
HKEY hkey = nullptr;
LSTATUS res = ::RegOpenKeyExA(HKEY_CURRENT_USER, sub_key, 0, KEY_WRITE, &hkey);
if (res != ERROR_SUCCESS) {
res = ::RegCreateKeyA(HKEY_CURRENT_USER, sub_key, &hkey);
}
if (res != ERROR_SUCCESS) {
return -1;
}
std::shared_ptr<void> close_key(nullptr, [&](void*) {
if (hkey != nullptr) {
::RegCloseKey(hkey);
hkey = nullptr;
}
});
res = ::RegSetValueExA(hkey, key, 0, REG_SZ, (BYTE*)value, strlen(value));
if (res != ERROR_SUCCESS) {
return -1;
}
return 1;
}
int CYLXQ_Register::GetValue(const char* key, char* value) {
BYTE* buffer = NULL;
HKEY hkey = nullptr;
LSTATUS res = ::RegOpenKeyExA(HKEY_CURRENT_USER, sub_key, 0, KEY_READ, &hkey);
if (res != ERROR_SUCCESS) {
return -1;
}
std::shared_ptr<void> close_key(nullptr, [&](void*) {
if (hkey != nullptr) {
::RegCloseKey(hkey);
hkey = nullptr;
}
});
DWORD type = REG_SZ;
DWORD size = 0;
res = ::RegQueryValueExA(hkey, key, 0, &type, nullptr, &size);
if (res != ERROR_SUCCESS || size <= 0) {
return -1;
}
std::vector<BYTE> value_data(size);
res = ::RegQueryValueExA(hkey, key, 0, &type, value_data.data(), &size);
if (res != ERROR_SUCCESS) {
return -1;
}
buffer = &value_data[0];
strcpy_s(value, value_data.size(), (char*)buffer);
return 1;
}
void CYLXQ_RegisterDemo() {
int ret;
char value[1024] = { 0 };
CYLXQ_Register reg(REGISTER_SUBKEY_DEFAULT);
ret = reg.SetValue("name", "TESTYangsy");
if (ret == 1) {
ret = reg.GetValue("name", value);
}
std::cout << value << std::endl;
}
运行结果: