C++实现获取Windows操作系统内核版本号

    作为一名Windows开发者,能熟练掌握WMI技术,在开发Windows应用程序的时候往往能够事半功倍。今天来给大家分享一个使用WMI来获取Windows操作系统内核版本号的例子。

    首先我们打开WMI测试器,连接ROOT\CIMV2命名空间,输入WQL查询语句SELECT * FROM Win32_OperatingSystem,

    C++实现获取Windows操作系统内核版本号_第1张图片

    然后在查询的结果里我们找到Version属性,发现内核版本号为10.0.16299,即为我们所需要的结果。

    C++实现获取Windows操作系统内核版本号_第2张图片

    那么,这个结果如何在程序中被使用,如何用C++语言来实现呢?首先我们要包含comdef.h和Wbemidl.h头文件,然后调用wbemuuid.lib库帮助我们实现WMI的功能,代码及测试程序如下:

    

#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

#pragma comment(lib, "wbemuuid.lib")

int GetSystemVersion(char* pSystemVersion)
{
	HRESULT hres;
	hres = CoInitializeEx(0, COINIT_MULTITHREADED);
	if (FAILED(hres))
	{
		return -1;
	}

	hres = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
	if (FAILED(hres))
	{
		CoUninitialize();
		return -1;
	}

	IWbemLocator *pLoc = NULL;
	hres = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *)&pLoc);
	if (FAILED(hres))
	{
		CoUninitialize();
		return -1;
	}

	IWbemServices *pSvc = NULL;
	hres = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);
	if (FAILED(hres))
	{
		pLoc->Release();
		CoUninitialize();
		return -1;
	}

	hres = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);
	if (FAILED(hres))
	{
		pSvc->Release();
		pLoc->Release();
		CoUninitialize();
		return -1;
	}

	IEnumWbemClassObject* pEnumerator = NULL;
	hres = pSvc->ExecQuery(bstr_t("WQL"), bstr_t("SELECT * FROM Win32_OperatingSystem"), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
	if (FAILED(hres))
	{
		pSvc->Release();
		pLoc->Release();
		CoUninitialize();
		return -1;
	}

	IWbemClassObject *pclsObj = NULL;
	ULONG uReturn = 0;
	while (pEnumerator)
	{
		HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
		if (0 == uReturn)
		{
			break;
		}

		VARIANT vtProp;
		hr = pclsObj->Get(L"Version", 0, &vtProp, 0, 0);
		WcharToChar(vtProp.bstrVal, pSystemVersion, 64);
		VariantClear(&vtProp);
		pclsObj->Release();
	}
	pSvc->Release();
	pLoc->Release();
	pEnumerator->Release();
	CoUninitialize();

	return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
	char pVersion[20];
	int retcode = 0;
	const char* s = "10.0.";
	char *p;
	retcode = GetSystemVersion(pVersion);
	if(retcode == 0)
	{
		p = strstr(pVersion,s);
		if(p!=NULL)
		{
			cout << "Current Windows is 2016 Server! " << endl;
			getchar();
			return 2;
		}
		else
		{
			cout << "Current Windows is not 2016 Server! " << endl;
			getchar();
			return 0;
		}
	}
	return 0;
}

你可能感兴趣的:(Windows开发)