VC++获取计算机Hardware Information (CPU ID, MainBoard Info, Hard Disk Serial, System Information)

时间:2021-08-23 05:33:59

转载:http://blog.csdn.net/yapingxin/article/details/50107799

转载:http://zhidao.baidu.com/link?url=A5K6NgF4pXAX2hp_NYCd97OEdHTBFlATxWb40HLv2XEbVjv2-LNNnBN1pheP51C_Rs0XYLAWSjySEfRWePKPW_

参考文章:http://www.codeproject.com/Articles/17973/How-To-Get-Hardware-Information-CPU-ID-MainBoard-I

1.计算机名称

 //计算机名称
void DisplayComputerNameEx()
{
TCHAR scComputerName[MAX_COMPUTERNAME_LENGTH* + ];
DWORD lnNameLength = MAX_COMPUTERNAME_LENGTH*; GetComputerNameEx(ComputerNameNetBIOS, scComputerName, &lnNameLength); _tprintf( _T("Computer name: %s\n"), scComputerName);
}

2.获取当前用户名(当前登录用户名)

 CString GetCurrentUserName()
{
CString strUserName; LPTSTR szBuffer=new wchar_t[];
DWORD dwSize=;
GetUserName(szBuffer,&dwSize);
strUserName=szBuffer; delete szBuffer; return strUserName;
}

3.处理器个数

 //处理器个数
void DisplayProcessorCount()
{
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo); _tprintf( _T("Number of processors: %d \n"), sysInfo.dwNumberOfProcessors);
}

4.CPU  ID

 //处理器ID
CString GetCPUID()
{ CString CPUID; unsigned long s1,s2; unsigned char vendor_id[]="------------"; char sel; sel=''; CString VernderID; CString MyCpuID,CPUID1,CPUID2; switch(sel) { case '': __asm{ xor eax,eax//eax=0:取Vendor信息 cpuid//取cpu id指令,可在Ring3级使用 mov dword ptr vendor_id,ebx mov dword ptr vendor_id[+],edx mov dword ptr vendor_id[+],ecx } VernderID.Format(_T("%s-"),vendor_id); __asm{ mov eax,01h//eax=1:取CPU序列号 xor edx,edx cpuid mov s1,edx mov s2,eax } CPUID1.Format(_T("%08X%08X"),s1,s2); __asm{ mov eax,03h xor ecx,ecx xor edx,edx cpuid mov s1,edx mov s2,ecx } CPUID2.Format(_T("%08X%08X"),s1,s2); break; case '': { __asm{ mov ecx,119h rdmsr or eax,00200000h wrmsr } } MessageBox(NULL,_T("CPU id is disabled."),_T("help"),MB_OK); break; } MyCpuID = CPUID1+CPUID2; CPUID = MyCpuID; return CPUID; }

5.硬盘ID

 #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(, COINIT_MULTITHREADED);
if (FAILED(hres))
{
cout << "Failed to initialize COM library. Error code = 0x"
<< hex << hres << endl;
return ; // 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,
-, // 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 ; // Program has failed.
} // Step 3: ---------------------------------------------------
// Obtain the initial locator to WMI ------------------------- IWbemLocator *pLoc = NULL; hres = CoCreateInstance(
CLSID_WbemLocator,
,
CLSCTX_INPROC_SERVER,
IID_IWbemLocator, (LPVOID *) &pLoc); if (FAILED(hres))
{
cout << "Failed to create IWbemLocator object."
<< " Err code = 0x"
<< hex << hres << endl;
CoUninitialize();
return ; // 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
, // Locale. NULL indicates current
NULL, // Security flags.
, // Authority (e.g. Kerberos)
, // Context object
&pSvc // pointer to IWbemServices proxy
); if (FAILED(hres))
{
cout << "Could not connect. Error code = 0x"
<< hex << hres << endl;
pLoc->Release();
CoUninitialize();
return ; // 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 ; // 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_PhysicalMedia"),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
&pEnumerator); if (FAILED(hres))
{
cout << "Query for physical media failed."
<< " Error code = 0x"
<< hex << hres << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
return ; // Program has failed.
} // Step 7: -------------------------------------------------
// Get the data from the query in step 6 ------------------- IWbemClassObject *pclsObj = NULL;
ULONG uReturn = ; while (pEnumerator)
{
HRESULT hr = pEnumerator->Next(WBEM_INFINITE, ,
&pclsObj, &uReturn); if( == uReturn)
{
break;
} VARIANT vtProp; // Get the value of the Name property
hr = pclsObj->Get(L"SerialNumber", , &vtProp, , ); wcout << "Serial Number : " << vtProp.bstrVal << endl;
VariantClear(&vtProp);
} // Cleanup
// ======== pSvc->Release();
pLoc->Release();
pEnumerator->Release();
pclsObj->Release();
CoUninitialize(); return ; // Program successfully completed.
}

6.主板ID

 //获取主板ID
BOOL GetMainBoardInfoByCmd(char* & lpszBaseBoard)
{
const long COMMAND_SIZE = ; // Command line output buffer
const DWORD WAIT_TIME = ; // INFINITE // The command to get mainboard serial number
TCHAR szFetCmd[] = _T("wmic BaseBoard get SerialNumber"); // Pre- information of mainboard serial number
const std::string strEnSearch = "SerialNumber"; BOOL fReturnCode = FALSE;
HANDLE hReadPipe = NULL; // Pipeline for READ
HANDLE hWritePipe = NULL; // Pipeline for WRITE
PROCESS_INFORMATION pi; // Process information
STARTUPINFO si; // Control-command window info
SECURITY_ATTRIBUTES sa; // Security attributes char szBuffer[COMMAND_SIZE + ] = { }; // Command line output buffer
std::string strBuffer;
DWORD count = ;
size_t pos = ;
size_t i = ;
size_t j = ; lpszBaseBoard = (char*)malloc((COMMAND_SIZE + )*sizeof(char));
memset(lpszBaseBoard, 0x00, (COMMAND_SIZE + )*sizeof(char)); memset(&pi, , sizeof(pi));
memset(&si, , sizeof(si));
memset(&sa, , sizeof(sa)); pi.hProcess = NULL;
pi.hThread = NULL;
si.cb = sizeof(STARTUPINFO);
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE; // Step 1: Create pipeline
fReturnCode = CreatePipe(&hReadPipe, &hWritePipe, &sa, );
if (!fReturnCode)
{
goto EXIT;
} // Step 2: Set command line window to be specific READ / WRITE pipeline
GetStartupInfo(&si);
si.hStdError = hWritePipe;
si.hStdOutput = hWritePipe;
si.wShowWindow = SW_HIDE; // hide command line window
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; // Step 3: Create process to get command line handle
fReturnCode = CreateProcess(NULL, szFetCmd, NULL, NULL, TRUE, , NULL, NULL, &si, &pi);
if (!fReturnCode)
{
goto EXIT;
} // Step 4: Get return back data
WaitForSingleObject(pi.hProcess, WAIT_TIME);
fReturnCode = ReadFile(hReadPipe, szBuffer, COMMAND_SIZE, &count, );
if (!fReturnCode)
{
goto EXIT;
} // Step 5: Search for mainboard serial number
fReturnCode = FALSE;
strBuffer = szBuffer;
pos = strBuffer.find(strEnSearch); if (pos < ) // NOT FOUND
{
goto EXIT;
}
else
{
strBuffer = strBuffer.substr(pos + strEnSearch.length());
} memset(szBuffer, 0x00, sizeof(szBuffer));
strcpy_s(szBuffer, strBuffer.c_str()); // Get ride of <space>, \r, \n
j = ;
for (i = ; i < strlen(szBuffer); i++)
{
if (szBuffer[i] != ' ' && szBuffer[i] != '\n' && szBuffer[i] != '\r')
{
lpszBaseBoard[j] = szBuffer[i];
j++;
}
} fReturnCode = TRUE; EXIT:
CloseHandle(hWritePipe);
CloseHandle(hReadPipe);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread); return(fReturnCode);
}

获取主板ID的用法

 {
. . . . . .
char* lpszMainBoardSN = NULL;
GetMainBoardInfoByCmd(lpszMainBoardSN); if (lpszMainBoardSN)
{
printf("%s\n", lpszMainBoardSN); free(lpszMainBoardSN);
lpszMainBoardSN = NULL;
}
else
{
printf("N/A\n");
} . . . . . .
}

示例Demo