registry.cpp

来自「C++写的加密程序,可对文件进行加密.」· C++ 代码 · 共 99 行

CPP
99
字号
#include "StdAfx.h"
#include "registry.h"
#include <stdio.h>

Registry::Registry(HKEY root, const char *subKey) : _rootKey(root), _regKey(0)
{
    strcpy(_subKey, subKey);   

	changeKey(root, subKey);
}

Registry::~Registry(void)
{
	RegCloseKey(_regKey);
}

bool Registry::readValue(const char *valueName, DWORD &type, char *ret, DWORD &len)
{
	if (!_validKey) return false;

	return RegQueryValueEx(_regKey, valueName, 0, &type, (LPBYTE)ret, &len) == ERROR_SUCCESS;
}

bool Registry::setValue(const char *valueName, const DWORD type, const char *data, DWORD dataLen, bool backupOld)
{
	if (!_validKey) return false;

    if (backupOld)
	{
	    DWORD oldType;
		DWORD oldLen = MAX_PATH;
		char content[MAX_PATH];
		if (readValue(valueName, oldType, content, oldLen))
		{
			char newValue[100];
			_snprintf(newValue, 100, "OLD_%s\0", valueName);
			
			setValue(newValue, oldType, content, oldLen);
		}
	}

	return RegSetValueEx(_regKey, valueName, 0, type, (CONST BYTE *)data, dataLen) == ERROR_SUCCESS;
}

bool Registry::restore(const char *valueName)
{
	DWORD bType, bLen = MAX_PATH;

	char bData[MAX_PATH];
	char bValue[100];

	_snprintf(bValue, 100, "OLD_%s\0", valueName);

	if (readValue(bValue, bType, bData, bLen))
	{
        setValue(valueName, bType, bData, bLen);
		
		// deleting original backup value.
		RegDeleteValue(_regKey, bValue);

		return true;
	}
	return false;


}

bool Registry::changeKey(HKEY root, const char *subKey)
{
	if (_validKey)
	{
		RegCloseKey(_regKey);
		_validKey = false;
	}

	if (RegCreateKey(HKEY_CLASSES_ROOT, subKey, &_regKey) == ERROR_SUCCESS)
	{
        _validKey = true;
	}
	
	return _validKey;
}

bool Registry::deleteKey(bool recursive)
{
	if (_validKey) 
	{
		RegCloseKey(_regKey);
		_regKey = 0;
		_validKey = false;
	}

	if (recursive)
	{
		return SHDeleteKey(_rootKey, _subKey) == ERROR_SUCCESS;
	}

	return RegDeleteKey(_rootKey, _subKey) == ERROR_SUCCESS;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?