// RegUtil.cpp: implementation of the CRegUtil class.
//

#include "stdafx.h"
#include "RegUtil.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CRegUtil::CRegUtil()
{
	m_hKey = NULL;
}

CRegUtil::~CRegUtil()
{
	if (!m_hKey)
		CloseKey();
}

BOOL CRegUtil::OpenKey(HKEY hKey, CString sKey)
{
	LONG lRet = RegOpenKeyEx(hKey, TEXT(sKey), 0, KEY_ALL_ACCESS, &m_hKey);
	if (lRet == ERROR_SUCCESS)
		return TRUE;
	else {
		DWORD dwDisp;

		lRet = RegCreateKeyEx(hKey, TEXT(sKey), 0, "REG_BINARY", REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, 0, &m_hKey, &dwDisp);
		if(lRet == ERROR_SUCCESS)
			return TRUE;
		else
			return FALSE;
	}
}

void CRegUtil::CloseKey()
{
	if (m_hKey)
		RegCloseKey(m_hKey);

	m_hKey = NULL;
}

BOOL CRegUtil::SetStrValue(CString sName, CString sValue)
{
	TCHAR szValue[MAX_PATH] = {'\0'};

	_tcscpy(szValue, sValue);

    LONG lRet = RegSetValueEx(m_hKey, TEXT(sName), NULL, REG_SZ, (PBYTE)&szValue, (DWORD)strlen(szValue));
	if (lRet == ERROR_SUCCESS)
		return TRUE;
	else
		return FALSE;
}

CString CRegUtil::GetStrValue(CString sName)
{
	DWORD dwType = REG_SZ;
	char  szValue[MAX_PATH];
	DWORD dwLength = sizeof(szValue);

	LONG lRet = RegQueryValueEx(m_hKey, TEXT(sName), NULL, &dwType, (PBYTE)szValue, &dwLength);
	if (lRet == ERROR_SUCCESS) {
		szValue[dwLength] = NULL;
		return CString(szValue);
	}
	else
		return "";
}

BOOL CRegUtil::SetNumValue(CString sName, UINT nValue)
{
    LONG lRet = RegSetValueEx(m_hKey, TEXT(sName), NULL, REG_DWORD, (PBYTE)&nValue, (DWORD)sizeof(nValue));
	if (lRet == ERROR_SUCCESS)
		return TRUE;
	else
		return FALSE;
}

UINT CRegUtil::GetNumValue(CString sName)
{
    DWORD dwType = REG_DWORD;
	DWORD dwValue;
    DWORD dwLength = sizeof(DWORD);

    LONG lRet = RegQueryValueEx(m_hKey, TEXT(sName), NULL, &dwType, (PBYTE)&dwValue, &dwLength);
	if (lRet == ERROR_SUCCESS)
		return (UINT)dwValue;
	else
		return 0;
}
