示例代码如下:

#include <iostream>   
#include <atlbase.h>
#include <Windows.h>
using namespace std;

int main()
{
    HKEY hKey = NULL;
    DWORD dwDisposition;
    LPCTSTR subKey = _T("SOFTWARE\\Foxit Software\\Foxit");
    DWORD dwOptions = REG_OPTION_NON_VOLATILE;
    // 创建注册表项
    // 注:KEY_ALL_ACCESS设置注册表的操作权限,也可以设置只读或只写
    auto re = RegCreateKeyEx(HKEY_LOCAL_MACHINE, subKey, 0, NULL, dwOptions, KEY_ALL_ACCESS, NULL, &hKey, &dwDisposition);
    if (ERROR_SUCCESS != re) {
        cout << "创建注册表失败, 错误代码:" << re << endl;
        return 0;
    }
    else {
        if (dwDisposition == REG_OPENED_EXISTING_KEY){
            cout << "打开一个存在的注册表项" << endl;
        }
        else if (dwDisposition == REG_CREATED_NEW_KEY){
            cout << "新建一个注册表项" << endl;
        }
    }

    // 写入注册表项
    WCHAR val[255] = _T("25");  // 用char类型会出现乱码
    int len = sizeof(WCHAR) * (wcslen(val)+1);
     re = RegSetValueEx(hKey, _T("use_count"), 0, REG_SZ, (const LPBYTE)val, len);
    if (re != ERROR_SUCCESS) {
        cout << "写入注册表失败" << endl;
    }

    // 读取注册表项
    WCHAR dwValue[255];
    DWORD dwSzType = REG_SZ;
    DWORD dwSize = sizeof(dwValue);
    re = RegQueryValueEx(hKey, _T("use_count"), 0, &dwSzType, (LPBYTE)dwValue, &dwSize);
    if (re != ERROR_SUCCESS){
        cout << "无法查询有关的注册表信息" << endl;
    }

    RegCloseKey(hKey);

    system("pause");
    return 0;
}

标签: windows, NULL, c++, include, cout, 注册表, KEY, dwDisposition

相关文章推荐

添加新评论,含*的栏目为必填