Registry Read/Write by VC

 
I just wrote a registry read/write program using VS2005 VC++
// SimonTestReg.cpp : Defines the entry point for the console application.
//
 
#include "stdafx.h"
#include <wtypes.h>
#include <atlstr.h>
 
void WriteRegistry();
 
int _tmain(int argc, _TCHAR* argv[])
{
    WriteRegistry();
    return 0;
}
 
void WriteRegistry()
{
    HKEY hSoftware = NULL;
    HKEY hProduct = NULL;
    LONG status;
 
    CString strSoftware = _T("Software");
 
    status = RegOpenKeyEx(HKEY_CURRENT_USER,
        (LPCWSTR)strSoftware,
        0,
        KEY_WRITE | KEY_READ,
        &hSoftware);
 
    if(status == ERROR_SUCCESS && hSoftware != NULL)
    {
        CString strCompanyAndProduct = _T("SimonCompany\\SimonProduct");
        status = RegOpenKeyEx(hSoftware,
            strCompanyAndProduct,
            0,
            KEY_WRITE | KEY_READ,
            &hProduct);
 
        if(status != ERROR_SUCCESS)
        {
            DWORD dw;
            status = RegCreateKeyEx(hSoftware, strCompanyAndProduct, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hProduct, &dw);
        }
    }
 
    if(hProduct)
    {
        DWORD typeDWORD = REG_DWORD;
        LPDWORD lpType = &typeDWORD;
 
        DWORD dataValue;
        DWORD dataSize;
 
        status = RegQueryValueEx(hProduct,
            _T("SimonValue"),
            NULL/*Reserved*/,
            lpType,
            (LPBYTE)&dataValue/*Output*/,
            &dataSize/*Output*/);
 
        DWORD theValueWanted = 2;
 
        if(status== ERROR_SUCCESS && dataValue != theValueWanted || status == ERROR_FILE_NOT_FOUND)
        {
            dataValue = theValueWanted;
            dataSize = sizeof(DWORD);
 
            status = RegSetValueEx(hProduct, _T("SimonValue"), NULL, REG_DWORD, (LPBYTE)&dataValue, dataSize);
        } 
    }
 
    if(hProduct)
        RegCloseKey(hProduct);
 
    if(hSoftware)
        RegCloseKey(hSoftware);
}
相關文章
相關標籤/搜索