#include "stdafx.h"
#include "RegObject.h"

CRegOp::CRegOp()
{
}

CRegOp::~CRegOp()
{
}

int CRegOp::ReadReg(HKEY hKey, LPCTSTR szDs, LPCTSTR szKey, int nDef)
{
	HKEY hRetKey;
	LONG lRet = RegOpenKeyEx(hKey, szDs, 0, KEY_READ|KEY_WOW64_64KEY, &hRetKey);   
	if(lRet != ERROR_SUCCESS)
		return nDef;
	
    DWORD dwType, dwCount, dwValue;
    LONG lResult = RegQueryValueEx(hRetKey, szKey, NULL, &dwType, NULL, &dwCount);
    if (lResult == ERROR_SUCCESS)
	{
		RegQueryValueEx(hRetKey, szKey, NULL, &dwType, (LPBYTE)&dwValue, &dwCount);
		nDef = (int)dwValue;
	}
	RegCloseKey(hRetKey);
	return nDef;
}

void CRegOp::ReadReg(HKEY hKey, LPCTSTR szDs, LPCTSTR szKey, LPCTSTR szDef, LPTSTR szBuf, int nBufLen)
{
	HKEY hRetKey;
	LONG lRet = RegOpenKeyEx(hKey, szDs, 0, KEY_READ|KEY_WOW64_64KEY, &hRetKey);   
	if(lRet != ERROR_SUCCESS)
	{
		lstrcpyn(szBuf, szDef, nBufLen);
		return;
	}
	
    DWORD dwType, dwCount;
    LONG lResult = RegQueryValueEx(hRetKey, szKey, NULL, &dwType, NULL, &dwCount);
    if (lResult == ERROR_SUCCESS)
	{
		if (dwCount > (DWORD)nBufLen-1)
			dwCount = nBufLen-1;
        RegQueryValueEx(hRetKey, szKey, NULL, &dwType, (LPBYTE)szBuf, &dwCount);
		RegCloseKey(hRetKey);
		return;
	}
	RegCloseKey(hRetKey);
	lstrcpyn(szBuf, szDef, nBufLen);
}

BOOL CRegOp::WriteReg(HKEY hKey, LPCTSTR szDs, LPCTSTR szKey, int nValue)
{
	HKEY hRetKey;
	if (CreateReg(hKey, szDs, &hRetKey) == FALSE)
		return FALSE;
	DWORD dwData = nValue;
	RegSetValueEx(hRetKey, szKey, NULL, REG_DWORD, (LPBYTE)&dwData, sizeof(DWORD)); 
	RegCloseKey(hRetKey);
	return TRUE;
}

BOOL CRegOp::WriteReg(HKEY hKey, LPCTSTR szDs, LPCTSTR szKey, LPCTSTR szValue, DWORD cbData, DWORD dwType)
{
	HKEY hRetKey;
	if (CreateReg(hKey, szDs, &hRetKey) == FALSE)
		return FALSE;
	RegSetValueEx(hRetKey, szKey, NULL, dwType, (LPBYTE)szValue, cbData);
	RegCloseKey(hRetKey);
	return TRUE;
}

BOOL CRegOp::IsExist(HKEY hKey, LPCTSTR szDs, LPCTSTR szKey)
{
	BOOL bReturn = TRUE;
	HKEY hRetKey;
	LONG lRet = RegOpenKeyEx(hKey, szDs, 0, KEY_READ|KEY_WOW64_64KEY, &hRetKey);   
	if(lRet != ERROR_SUCCESS)
		return FALSE;
	
    DWORD dwType, dwCount;
    LONG lResult = RegQueryValueEx(hRetKey, szKey, NULL, &dwType, NULL, &dwCount);
    if (lResult != ERROR_SUCCESS)
		bReturn = FALSE;
	RegCloseKey(hRetKey);
	return bReturn;
}

BOOL CRegOp::CreateReg(HKEY hKey, LPCTSTR lpszSubKey, PHKEY pResult)
{
	if (hKey==NULL || lpszSubKey==NULL || lstrlen(lpszSubKey)==0)
		return FALSE;
	
	HKEY hTemp;
	DWORD dwDisposition;
	LONG lResult = RegCreateKeyEx(hKey, lpszSubKey, 0, _T(""), REG_OPTION_NON_VOLATILE, 
		KEY_ALL_ACCESS|KEY_WOW64_64KEY, NULL, &hTemp, &dwDisposition);
	if (lResult == ERROR_SUCCESS)
	{
		if (pResult==NULL)
			RegCloseKey(hTemp);
		else
			*pResult = hTemp;
		return TRUE;
	}

	return FALSE;
}