C++ 读写注册表

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#include <windows.h>
#include <iostream>
using std::cout; using std::endl;

HKEY OpenKey(HKEY hRootKey, wchar_t* strKey)
{
    HKEY hKey;
    LONG nError = RegOpenKeyEx(hRootKey, strKey, NULL, KEY_ALL_ACCESS, &hKey);

    if (nError==ERROR_FILE_NOT_FOUND)
    {
        cout << "Creating registry key: " << strKey << endl;
        nError = RegCreateKeyEx(hRootKey, strKey, NULL, NULL, REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS,NULL, &hKey, NULL);
    }

    if (nError)
        cout << "Error: " << nError << " Could not find or create " << strKey << endl;

    return hKey;
}

void SetVal(HKEY hKey, LPCTSTR lpValue, DWORD data)
{
    LONG nError = RegSetValueEx(hKey, lpValue, NULL, REG_DWORD, (LPBYTE)&data, sizeof(DWORD));

    if (nError)
        cout << "Error: " << nError << " Could not set registry value: " << (char*)lpValue << endl;
}

DWORD GetVal(HKEY hKey, LPCTSTR lpValue)
{
    DWORD data;        DWORD size = sizeof(data);    DWORD type = REG_DWORD;
    LONG nError = RegQueryValueEx(hKey, lpValue, NULL, &type, (LPBYTE)&data, &size);

    if (nError==ERROR_FILE_NOT_FOUND)
        data = 0; // The value will be created and set to data next time SetVal() is called.
    else if (nError)
        cout << "Error: " << nError << " Could not get registry value " << (char*)lpValue << endl;

    return data;
}

int main()
{
    static DWORD v1, v2;

    HKEY hKey = OpenKey(HKEY_LOCAL_MACHINE,L"SOFTWARE\\MyCompany");

    v1 = GetVal(hKey, L"Value1");
    v2 = GetVal(hKey, L"Value2");

    v1 += 5;
    v2 += 2;

    SetVal(hKey, L"Value1", v1);
    SetVal(hKey, L"Value2", v2);

    RegCloseKey(hKey);

    return 0;
}

CopyFrom: http://www.cplusplus.com/forum/windows/58636/

转载于:https://www.cnblogs.com/albertofwb/p/6188770.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值