C++ 读取windows注册表 值

C++ 读取windows注册表 值_第1张图片

#include 
#include 
#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;
}

编译结果如下:

C++ 读取windows注册表 值_第2张图片

Tip:

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

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

你可能感兴趣的:(C++&QT)