VS 2019 MFC 通过WMI技术读取计算机CPU序列号,硬盘序列号,BIOS序列号,主板序列号,系统名称以及网卡MAC地址

35 篇文章 8 订阅

 经行了简单的封装,江功能全部封装到了类文件。

 封装类文件H头文件

#ifndef _H_GETSYSTEMHARDWAREID
#define _H_GETSYSTEMHARDWAREID
#include"targetver.h"
#include<wbemcli.h>
#include<string.h>
#include <iostream>
#include <Windows.h>
#include <comdef.h>
#include <Wbemidl.h>
#include "wincred.h"
#pragma comment(lib, "credui.lib")
#pragma comment(lib,"wbemuuid.lib")
using namespace std;
#pragma once
class GetSysTemHardWareID
{
public:
	virtual ~GetSysTemHardWareID();
	GetSysTemHardWareID(wchar_t* WMI_Namespace = L"ROOT\\CIMV2");
public:
	void Get_CpuId(CString& dest);
	void Get_DiskDriveId(CString& dest);
	void Get_MacAddress(CString& dest);
	void Get_OsName(CString& dest);
	void Get_BaseBoardId(CString &dest);
	void Get_BiosSerialId(CString &dest);
	HRESULT hres;
private:
	IWbemServices* pSvc;
	IWbemLocator*  pLoc; 
	bool ExecQueryValue(char* strQueryLanguage, char* strQuery, IEnumWbemClassObject** pEnumerator);
private:
protected:
};
#endif // !_H_GETSYSTEMHARDWAREID

封装类CPP实现文件

#include "pch.h"
#include "GetSysTemHardWareID.h"
#include <vector>
#include <iostream> 
#include <list>
using namespace std;
GetSysTemHardWareID::GetSysTemHardWareID(wchar_t* WMI_Namespace)
{
     pSvc = NULL;
     pLoc = NULL;
     hres = NULL;

    hres =  CoInitializeEx(0, COINIT_MULTITHREADED); 
    if (FAILED(hres))
    {
        printf("Failed to initialize COM library. Error code = 0x");
    }
    hres =  CoInitializeSecurity(
        NULL, 
        -1,                         
        NULL,                       
        NULL,                       
        RPC_C_AUTHN_LEVEL_DEFAULT,   
        RPC_C_IMP_LEVEL_IMPERSONATE, 
        NULL,                        
        EOAC_NONE,                  
        NULL                        
        );
                      
    if (FAILED(hres))
    {
        printf("Failed to initialize security. Error code = 0x");
        CoUninitialize();
    }
    hres = CoCreateInstance(
        CLSID_WbemLocator,             
        0, 
        CLSCTX_INPROC_SERVER, 
        IID_IWbemLocator, (LPVOID *) &pLoc);
 
    if (FAILED(hres))
    {
        printf("Failed to create IWbemLocator object.");        
        CoUninitialize();
          
    }
    hres = pLoc->ConnectServer(
         _bstr_t(WMI_Namespace), 
         NULL,                   
         NULL,                   
         0,                      
         NULL,                 
         0,                       
         0,                      
         &pSvc                  
         );
    
    if (FAILED(hres))
    {
        printf("Could not connect. Error code = 0x");
        pLoc->Release();     
        CoUninitialize();        
    }
    printf ("Connected to ROOT\\CIMV2 WMI namespace") ;

    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))
    {
        printf("Could not set proxy blanket. Error code = 0x");
        pSvc->Release();
        pLoc->Release();     
        CoUninitialize();              
    }
}
GetSysTemHardWareID::~GetSysTemHardWareID()
{
	pSvc->Release();
	pLoc->Release();
    CoUninitialize();
    hres = NULL;
}

void GetSysTemHardWareID::Get_CpuId(CString& dest)
{
	IEnumWbemClassObject* pEnumerator = NULL;
	ExecQueryValue("WQL", "SELECT * FROM Win32_Processor", &pEnumerator);
	IWbemClassObject* pclsObj = NULL;
	ULONG uReturn = 0;
	while (pEnumerator)
	{
		HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,
		&pclsObj, &uReturn);
		if (0 == uReturn)
		{
			break;
		}
		VARIANT vtProp;
        vtProp.vt = VT_BSTR;
		hr = pclsObj->Get(L"ProcessorId", 0, &vtProp, 0, 0);
        printf("ProcessorId:\n%ws", vtProp.bstrVal);
        printf("\n");
		dest = vtProp.bstrVal;
		VariantClear(&vtProp);
		pclsObj->Release();
	}
	pEnumerator->Release();
}

void GetSysTemHardWareID::Get_DiskDriveId(CString& dest)
{
	IEnumWbemClassObject* pEnumerator = NULL;
	ExecQueryValue("WQL", "SELECT * FROM Win32_DiskDrive WHERE (SerialNumber IS NOT NULL) AND (MediaType LIKE 'Fixed hard disk%')", &pEnumerator);
	IWbemClassObject* pclsObj = NULL;
	ULONG uReturn = 0;
    int i = 0;
    CString strN;
	while (pEnumerator)
	{
        i++;
		HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,
			&pclsObj, &uReturn);
		if (0 == uReturn)
		{
			break;
		}
		VARIANT vtProp;
        vtProp.vt = VT_BSTR;
		hr = pclsObj->Get(L"SerialNumber", 0, &vtProp, 0,0);  
        strN = strN + vtProp.bstrVal+_T(";");
        dest = vtProp.bstrVal;
        dest.Replace(_T(" "), _T(""));
        strN.Replace(_T(" "),_T(""));
        printf("SerialNumber[%d]:\n%ws", i, dest.GetString());
        printf("\n");
		VariantClear(&vtProp);
		pclsObj->Release();
	}
	pEnumerator->Release();
    i = 0;
    dest = strN;
}

void GetSysTemHardWareID::Get_MacAddress(CString& dest)
{
        IEnumWbemClassObject* pEnumerator = NULL;
        ExecQueryValue("WQL", "SELECT * FROM Win32_NetworkAdapter WHERE (MACAddress IS NOT NULL) AND (NOT (PNPDeviceID LIKE 'ROOT%'))", &pEnumerator);
        IWbemClassObject* pclsObj = NULL;
        ULONG uReturn = 0;
        vector<CString> MACAddress;
        while (pEnumerator)
        {
            HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,
            &pclsObj, &uReturn);
            if (0 == uReturn)
            {
                break;
            }
            VARIANT vtProp;
            VARIANT vtProp2;
            vtProp.vt = VT_BSTR;
            vtProp2.vt = VT_BSTR;
            hr = pclsObj->Get(L"Description", 0, &vtProp2, 0, 0);
            printf("Description:\n%ws", vtProp2.bstrVal);
            printf("\n");
            dest = vtProp2.bstrVal;
            dest += _T(" ; ");  
            pclsObj->Get(L"MACAddress", 0, &vtProp, 0, 0);
            MACAddress.push_back((CString)(vtProp.bstrVal));
            printf("MACAddress:\n%ws", vtProp.bstrVal);
            printf("\n");
            VariantClear(&vtProp);
            pclsObj->Release();
            break;
        }
        if (MACAddress.size() >= 1)
        {
            dest= dest+MACAddress[0];
        }
      /*  else if (MACAddress.size()>1)
        {
            for (size_t i = 0; i < MACAddress.size(); i++)
            {
                dest = dest + MACAddress[i];
            }
        }*/
        MACAddress.clear();
        pEnumerator->Release();
}

void GetSysTemHardWareID::Get_OsName(CString& dest)
{
	IEnumWbemClassObject* pEnumerator=NULL ;
	ExecQueryValue("WQL", "SELECT * FROM Win32_OperatingSystem", &pEnumerator);
	IWbemClassObject* pclsObj = NULL;
	ULONG uReturn = 0;
	while (pEnumerator)
	{
        HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,
		&pclsObj, &uReturn);
		if (0 == uReturn)
		{
			break;
		}
		VARIANT vtProp;
        vtProp.vt = VT_BSTR;
        hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
        printf("OS NAME:\n%ws", vtProp.bstrVal);
        printf("\n");
		dest = vtProp.bstrVal;
		VariantClear(&vtProp);
		pclsObj->Release();
		break;
	}
    pEnumerator->Release();
}

void GetSysTemHardWareID::Get_BaseBoardId(CString &dest)
{
    IEnumWbemClassObject* pEnumerator = NULL;
    ExecQueryValue("WQL", "SELECT * FROM Win32_BaseBoard WHERE (SerialNumber IS NOT NULL)", &pEnumerator);
    IWbemClassObject* pclsObj = NULL;
    ULONG uReturn = 0;
    while (pEnumerator)
    {
        HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,
            &pclsObj, &uReturn);
        if (0 == uReturn)
        {
            break;
        }
        VARIANT vtProp;
        vtProp.vt = VT_BSTR;
        hr = pclsObj->Get(L"SerialNumber", 0, &vtProp, 0, 0);
        printf("Board SerialNumber:\n%ws", vtProp.bstrVal);
        printf("\n");
        dest += _T("BaseBoardId:");
        dest += vtProp.bstrVal;
        VariantClear(&vtProp);
        pclsObj->Release();
        break;
    }
    pEnumerator->Release();
}

void GetSysTemHardWareID::Get_BiosSerialId(CString& dest)
{
    IEnumWbemClassObject* pEnumerator = NULL;
    ExecQueryValue("WQL", "SELECT * FROM Win32_BIOS WHERE SerialNumber IS NOT NULL", &pEnumerator);
    IWbemClassObject* pclsObj = NULL;
    ULONG uReturn = 0;
    while (pEnumerator)
    {
        HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,
            &pclsObj, &uReturn);
        if (0 == uReturn)
        {
            break;
        }
        VARIANT vtProp;
        vtProp.vt = VT_BSTR;
        hr = pclsObj->Get(L"SerialNumber", 0, &vtProp, 0, 0);
        printf("BIOS SerialNumber:\n%ws", vtProp.bstrVal);
        printf("\n");
        dest += _T("BIOSSerialId:");
        dest += vtProp.bstrVal;
        VariantClear(&vtProp);
        pclsObj->Release();
    }
    pEnumerator->Release();
}

bool GetSysTemHardWareID::ExecQueryValue(char* strQueryLanguage, char* strQuery, IEnumWbemClassObject** pEnumerator)
{
    HRESULT hre = pSvc->ExecQuery(
		bstr_t(strQueryLanguage),
		bstr_t(strQuery),
		WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
		NULL,
		pEnumerator);
	if (FAILED(hres))
	{
		printf("Query for operating system name failed.");
		pSvc->Release();
		pLoc->Release();
		CoUninitialize();
		return FALSE; 
	}
	return true;
}

重要说明:本例程参考《MSDN Library for Visual Studio 2008 SP1 简体中文》类库文件说明,如下为《MSDN Library for Visual Studio 2008 SP1 简体中文》中对WMI技术的说明,在如下说明的第6步和第7步为读取PC机系统名称例程。

#define _WIN32_DCOM
#include <iostream>
using namespace std;
#include <comdef.h>
#include <Wbemidl.h>

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

int main(int argc, char **argv)
{
    HRESULT hres;

    // Step 1: --------------------------------------------------
    // Initialize COM. ------------------------------------------

    hres =  CoInitializeEx(0, COINIT_MULTITHREADED); 
    if (FAILED(hres))
    {
        cout << "Failed to initialize COM library. Error code = 0x" 
            << hex << hres << endl;
        return 1;                  // Program has failed.
    }

    // Step 2: --------------------------------------------------
    // Set general COM security levels --------------------------
    // Note: If you are using Windows 2000, you need to specify -
    // the default authentication credentials for a user by using
    // a SOLE_AUTHENTICATION_LIST structure in the pAuthList ----
    // parameter of CoInitializeSecurity ------------------------

    hres =  CoInitializeSecurity(
        NULL, 
        -1,                          // COM authentication
        NULL,                        // Authentication services
        NULL,                        // Reserved
        RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication 
        RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation  
        NULL,                        // Authentication info
        EOAC_NONE,                   // Additional capabilities 
        NULL                         // Reserved
        );

                      
    if (FAILED(hres))
    {
        cout << "Failed to initialize security. Error code = 0x" 
            << hex << hres << endl;
        CoUninitialize();
        return 1;                    // Program has failed.
    }
    
    // Step 3: ---------------------------------------------------
    // Obtain the initial locator to WMI -------------------------

    IWbemLocator *pLoc = NULL;

    hres = CoCreateInstance(
        CLSID_WbemLocator,             
        0, 
        CLSCTX_INPROC_SERVER, 
        IID_IWbemLocator, (LPVOID *) &pLoc);
 
    if (FAILED(hres))
    {
        cout << "Failed to create IWbemLocator object."
            << " Err code = 0x"
            << hex << hres << endl;
        CoUninitialize();
        return 1;                 // Program has failed.
    }

    // Step 4: -----------------------------------------------------
    // Connect to WMI through the IWbemLocator::ConnectServer method

    IWbemServices *pSvc = NULL;
	
    // Connect to the root\cimv2 namespace with
    // the current user and obtain pointer pSvc
    // to make IWbemServices calls.
    hres = pLoc->ConnectServer(
         _bstr_t(L"ROOT\\CIMV2"), // Object path of WMI namespace
         NULL,                    // User name. NULL = current user
         NULL,                    // User password. NULL = current
         0,                       // Locale. NULL indicates current
         NULL,                    // Security flags.
         0,                       // Authority (e.g. Kerberos)
         0,                       // Context object 
         &pSvc                    // pointer to IWbemServices proxy
         );
    
    if (FAILED(hres))
    {
        cout << "Could not connect. Error code = 0x" 
             << hex << hres << endl;
        pLoc->Release();     
        CoUninitialize();
        return 1;                // Program has failed.
    }

    cout << "Connected to ROOT\\CIMV2 WMI namespace" << endl;


    // Step 5: --------------------------------------------------
    // Set security levels on the proxy -------------------------

    hres = CoSetProxyBlanket(
       pSvc,                        // Indicates the proxy to set
       RPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxx
       RPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxx
       NULL,                        // Server principal name 
       RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx 
       RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
       NULL,                        // client identity
       EOAC_NONE                    // proxy capabilities 
    );

    if (FAILED(hres))
    {
        cout << "Could not set proxy blanket. Error code = 0x" 
            << hex << hres << endl;
        pSvc->Release();
        pLoc->Release();     
        CoUninitialize();
        return 1;               // Program has failed.
    }

    // Step 6: --------------------------------------------------
    // Use the IWbemServices pointer to make requests of WMI ----

    // For example, get the name of the operating system
    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))
    {
        cout << "Query for operating system name failed."
            << " Error code = 0x" 
            << hex << hres << endl;
        pSvc->Release();
        pLoc->Release();
        CoUninitialize();
        return 1;               // Program has failed.
    }

    // Step 7: -------------------------------------------------
    // Get the data from the query in step 6 -------------------
 
    IWbemClassObject *pclsObj;
    ULONG uReturn = 0;
   
    while (pEnumerator)
    {
        HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, 
            &pclsObj, &uReturn);

        if(0 == uReturn)
        {
            break;
        }

        VARIANT vtProp;

        // Get the value of the Name property
        hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
        wcout << " OS Name : " << vtProp.bstrVal << endl;
        VariantClear(&vtProp);
    }

    // Cleanup
    // ========
    
    pSvc->Release();
    pLoc->Release();
    pEnumerator->Release();
    pclsObj->Release();
    CoUninitialize();

    return 0;   // Program successfully completed.
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值