C++实现读写注册表

文章提供了一个名为CYLXQ_Register的C++类,用于在Windows环境下进行注册表的读写操作。类中包含构造函数初始化子键,以及设置和获取值的方法。示例代码展示了如何使用该类进行注册表的写入和读取。
摘要由CSDN通过智能技术生成

定义头文件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;
}

运行结果:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值