C++ 读取windows注册表 值

#include <iostream>
#include <assert.h>
#include "windows.h"
#include "tchar.h"
#include "conio.h"
#include "stdio.h"
using namespace std;

void wcharTochar(const wchar_t *wchar, char *chr, int length)
{
	WideCharToMultiByte(CP_ACP, 0, wchar, -1,
		chr, length, NULL, NULL);
}

bool OpenRegKey(HKEY& hRetKey)
{
	LPCWSTR sw = _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\Bandizip.exe");//_T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\Bandizip.exe");
	wprintf(L"SW is %s\n",sw);
	if (ERROR_SUCCESS == RegOpenKey(HKEY_LOCAL_MACHINE, sw, &hRetKey))
	{
		return true;
	}
	printf("OpenRegKey return is false!\n");
	return false;
}

bool QueryRegKey(LPCWSTR strSubKey, LPCWSTR strValueName, char *strValue,int length)//这里是传3个参数
{
	DWORD dwType = REG_SZ;//定义数据类型
	DWORD dwLen = MAX_PATH;

	wchar_t data[MAX_PATH];
	HKEY hKey;
	HKEY hSubKey;
	if (OpenRegKey(hKey))
	{
		if (ERROR_SUCCESS == RegOpenKey(HKEY_LOCAL_MACHINE, strSubKey, &hSubKey))
		{
			TCHAR buf[256] = { 0 };
			
			if (ERROR_SUCCESS == RegQueryValueEx(hSubKey, strValueName, 0, &dwType, (LPBYTE)data, &dwLen))
			{
				wcharTochar(data, strValue,length);
				wprintf(L"data = %s,len= %d\n", data,strlen((const char *)data));
				RegCloseKey(hKey); //关闭注册表
				return true;
			}
		}
		RegCloseKey(hKey); //关闭注册表
	}

	return false;
}
int main()
{
	HKEY  hKey = NULL;
	string result;
	LPCWSTR strSubKey= _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\Bandizip.exe");
	LPCWSTR strValueName= _T("Path");
	char strValue[256];
	int length = 256;
	bool status = QueryRegKey(strSubKey,strValueName,strValue,length);
	printf("status is %d\n", status);
	printf("result is %s\n", strValue);
	return 0;
}

编译结果如下:

Tip:

输出为软件的安装路径,所以在类型选择上,选择宽字符的wchar_t;

RegQueryValueEx函数默认第5个类型是,LPBYTE,若定义选择此,输入将只有一个字母C

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

闫有尽意无琼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值