当前位置:   article > 正文

【c++】获取电脑硬件信息(操作系统,CPU,内存,GPU,显卡驱动,显示设备分辨率)_c++ 获取硬件信息

c++ 获取硬件信息

操作系统,CPU,内存,GPU

参考 C/C++获取操作系统、CPU、内存信息、硬盘、IP和MAC、进程信息(windows和linux)

显卡驱动

参考  【C++】WMI获取系统硬件信息(CPU/DISK/NetWork etc)

  1. #include <iostream>
  2. #include <string>
  3. #include <string.h>
  4. #include <winsock2.h> // include must before window.h
  5. #include <iphlpapi.h>
  6. #include <windows.h>
  7. #include <DXGI.h>
  8. #include <vector>
  9. #pragma comment(lib, "iphlpapi.lib")
  10. #pragma comment(lib, "DXGI.lib")
  11. #pragma warning(disable: 4996) // avoid GetVersionEx to be warned
  12. #define _WIN32_DCOM
  13. using namespace std;
  14. #include <comdef.h>
  15. #include <Wbemidl.h>
  16. #pragma comment(lib, "wbemuuid.lib")
  17. // ***** global macros ***** //
  18. static const int kMaxInfoBuffer = 256;
  19. #define GBYTES 1073741824
  20. #define MBYTES 1048576
  21. #define KBYTES 1024
  22. #define DKBYTES 1024.0
  23. /*显卡驱动信息*/
  24. void getDriver() {
  25. HRESULT hres;
  26. // Step 1: --------------------------------------------------
  27. // Initialize COM. ------------------------------------------
  28. hres = CoInitializeEx(0, COINIT_MULTITHREADED);
  29. if (FAILED(hres))
  30. {
  31. cout << "Failed to initialize COM library. Error code = 0x"
  32. << hex << hres << endl;
  33. return; // Program has failed.
  34. }
  35. // Step 2: --------------------------------------------------
  36. // Set general COM security levels --------------------------
  37. hres = CoInitializeSecurity(
  38. NULL,
  39. -1, // COM authentication
  40. NULL, // Authentication services
  41. NULL, // Reserved
  42. RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication
  43. RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation
  44. NULL, // Authentication info
  45. EOAC_NONE, // Additional capabilities
  46. NULL // Reserved
  47. );
  48. if (FAILED(hres))
  49. {
  50. cout << "Failed to initialize security. Error code = 0x"
  51. << hex << hres << endl;
  52. CoUninitialize();
  53. return; // Program has failed.
  54. }
  55. // Step 3: ---------------------------------------------------
  56. // Obtain the initial locator to WMI -------------------------
  57. IWbemLocator* pLoc = NULL;
  58. hres = CoCreateInstance(
  59. CLSID_WbemLocator,
  60. 0,
  61. CLSCTX_INPROC_SERVER,
  62. IID_IWbemLocator, (LPVOID*)&pLoc);
  63. if (FAILED(hres))
  64. {
  65. cout << "Failed to create IWbemLocator object."
  66. << " Err code = 0x"
  67. << hex << hres << endl;
  68. CoUninitialize();
  69. return; // Program has failed.
  70. }
  71. // Step 4: -----------------------------------------------------
  72. // Connect to WMI through the IWbemLocator::ConnectServer method
  73. IWbemServices* pSvc = NULL;
  74. // Connect to the root\cimv2 namespace with
  75. // the current user and obtain pointer pSvc
  76. // to make IWbemServices calls.
  77. hres = pLoc->ConnectServer(
  78. _bstr_t(L"ROOT\\CIMV2"), // Object path of WMI namespace
  79. NULL, // User name. NULL = current user
  80. NULL, // User password. NULL = current
  81. 0, // Locale. NULL indicates current
  82. NULL, // Security flags.
  83. 0, // Authority (for example, Kerberos)
  84. 0, // Context object
  85. &pSvc // pointer to IWbemServices proxy
  86. );
  87. if (FAILED(hres))
  88. {
  89. cout << "Could not connect. Error code = 0x"
  90. << hex << hres << endl;
  91. pLoc->Release();
  92. CoUninitialize();
  93. return; // Program has failed.
  94. }
  95. //cout << "Connected to ROOT\\CIMV2 WMI namespace" << endl;
  96. // Step 5: --------------------------------------------------
  97. // Set security levels on the proxy -------------------------
  98. hres = CoSetProxyBlanket(
  99. pSvc, // Indicates the proxy to set
  100. RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx
  101. RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx
  102. NULL, // Server principal name
  103. RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx
  104. RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
  105. NULL, // client identity
  106. EOAC_NONE // proxy capabilities
  107. );
  108. if (FAILED(hres))
  109. {
  110. cout << "Could not set proxy blanket. Error code = 0x"
  111. << hex << hres << endl;
  112. pSvc->Release();
  113. pLoc->Release();
  114. CoUninitialize();
  115. return; // Program has failed.
  116. }
  117. // Step 6: --------------------------------------------------
  118. // Use the IWbemServices pointer to make requests of WMI ----
  119. // For example, get the name of the operating system
  120. IEnumWbemClassObject* pEnumerator = NULL;
  121. hres = pSvc->ExecQuery(
  122. bstr_t("WQL"),
  123. bstr_t("SELECT * FROM Win32_VideoController"),
  124. WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
  125. NULL,
  126. &pEnumerator);
  127. if (FAILED(hres))
  128. {
  129. cout << "Query for operating system name failed."
  130. << " Error code = 0x"
  131. << hex << hres << endl;
  132. pSvc->Release();
  133. pLoc->Release();
  134. CoUninitialize();
  135. return; // Program has failed.
  136. }
  137. // Step 7: -------------------------------------------------
  138. // Get the data from the query in step 6 -------------------
  139. IWbemClassObject* pclsObj = NULL;
  140. ULONG uReturn = 0;
  141. while (pEnumerator)
  142. {
  143. HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,
  144. &pclsObj, &uReturn);
  145. if (0 == uReturn)
  146. {
  147. break;
  148. }
  149. VARIANT vtProp;
  150. // Get the value of the Name property
  151. hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
  152. wcout << "VideoController Name:" << vtProp.bstrVal << endl;
  153. hr = pclsObj->Get(L"DriverVersion", 0, &vtProp, 0, 0);
  154. wcout << "VideoController DriverVersion:" << vtProp.bstrVal << endl;
  155. VariantClear(&vtProp);
  156. pclsObj->Release();
  157. }
  158. // Cleanup
  159. // ========
  160. pSvc->Release();
  161. pLoc->Release();
  162. pEnumerator->Release();
  163. CoUninitialize();
  164. }
  165. /*操作系统版本*/
  166. void getOsInfo()
  167. {
  168. // get os name according to version number
  169. OSVERSIONINFO osver = { sizeof(OSVERSIONINFO) };
  170. GetVersionEx(&osver);
  171. std::string os_name;
  172. if (osver.dwMajorVersion == 5 && osver.dwMinorVersion == 0)
  173. os_name = "Windows 2000";
  174. else if (osver.dwMajorVersion == 5 && osver.dwMinorVersion == 1)
  175. os_name = "Windows XP";
  176. else if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 0)
  177. os_name = "Windows 2003";
  178. else if (osver.dwMajorVersion == 5 && osver.dwMinorVersion == 2)
  179. os_name = "windows vista";
  180. else if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 1)
  181. os_name = "windows 7";
  182. else if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 2)
  183. os_name = "windows 10";
  184. std::cout << "operating system: " << os_name << std::endl;
  185. //dwMajorVersion 操作系统的主版本号,dwMinorVersion 操作系统的副版本号
  186. //std::cout << "os version: " << osver.dwMajorVersion << '.' << osver.dwMinorVersion << std::endl;
  187. }
  188. #ifdef _WIN64
  189. // method 2: usde winapi, works for x86 and x64
  190. #include <intrin.h>
  191. /*CPU*/
  192. void getCpuInfo()
  193. {
  194. int cpuInfo[4] = { -1 };
  195. char cpu_manufacture[32] = { 0 };
  196. char cpu_type[32] = { 0 };
  197. char cpu_freq[32] = { 0 };
  198. __cpuid(cpuInfo, 0x80000002);
  199. memcpy(cpu_manufacture, cpuInfo, sizeof(cpuInfo));
  200. __cpuid(cpuInfo, 0x80000003);
  201. memcpy(cpu_type, cpuInfo, sizeof(cpuInfo));
  202. __cpuid(cpuInfo, 0x80000004);
  203. memcpy(cpu_freq, cpuInfo, sizeof(cpuInfo));
  204. //std::cout << "CPU manufacture: " << cpu_manufacture << std::endl;
  205. //std::cout << "CPU type: " << cpu_type << std::endl;
  206. //std::cout << "CPU main frequency: " << cpu_freq << std::endl;
  207. std::cout << "CPU:" << cpu_manufacture << cpu_type << cpu_freq << std::endl;
  208. }
  209. #else
  210. // mothed 1: this kind asm embedded in code only works in x86 build
  211. // save 4 register variables
  212. DWORD deax;
  213. DWORD debx;
  214. DWORD decx;
  215. DWORD dedx;
  216. // init cpu in assembly language
  217. void initCpu(DWORD veax)
  218. {
  219. __asm
  220. {
  221. mov eax, veax
  222. cpuid
  223. mov deax, eax
  224. mov debx, ebx
  225. mov decx, ecx
  226. mov dedx, edx
  227. }
  228. }
  229. long getCpuFreq()
  230. {
  231. int start, over;
  232. _asm
  233. {
  234. RDTSC
  235. mov start, eax
  236. }
  237. Sleep(50);
  238. _asm
  239. {
  240. RDTSC
  241. mov over, eax
  242. }
  243. return (over - start) / 50000;
  244. }
  245. std::string getManufactureID()
  246. {
  247. char manuID[25];
  248. memset(manuID, 0, sizeof(manuID));
  249. initCpu(0);
  250. memcpy(manuID + 0, &debx, 4); // copy to array
  251. memcpy(manuID + 4, &dedx, 4);
  252. memcpy(manuID + 8, &decx, 4);
  253. return manuID;
  254. }
  255. std::string getCpuType()
  256. {
  257. const DWORD id = 0x80000002; // start 0x80000002 end to 0x80000004
  258. char cpuType[49];
  259. memset(cpuType, 0, sizeof(cpuType));
  260. for (DWORD t = 0; t < 3; t++)
  261. {
  262. initCpu(id + t);
  263. memcpy(cpuType + 16 * t + 0, &deax, 4);
  264. memcpy(cpuType + 16 * t + 4, &debx, 4);
  265. memcpy(cpuType + 16 * t + 8, &decx, 4);
  266. memcpy(cpuType + 16 * t + 12, &dedx, 4);
  267. }
  268. return cpuType;
  269. }
  270. void getCpuInfo()
  271. {
  272. //std::cout << "CPU manufacture: " << getManufactureID() << std::endl;
  273. //std::cout << "CPU type: " << getCpuType() << std::endl;
  274. //std::cout << "CPU main frequency: " << getCpuFreq() << "MHz" << std::endl;
  275. std::cout << "CPU :" << getManufactureID() << getCpuType() << getCpuFreq() << std::endl;
  276. }
  277. #endif
  278. /*内存*/
  279. void getMemoryInfo()
  280. {
  281. std::string memory_info;
  282. MEMORYSTATUSEX statusex;
  283. statusex.dwLength = sizeof(statusex);
  284. if (GlobalMemoryStatusEx(&statusex))
  285. {
  286. unsigned long long total = 0, remain_total = 0, avl = 0, remain_avl = 0;
  287. double decimal_total = 0, decimal_avl = 0;
  288. remain_total = statusex.ullTotalPhys % GBYTES;
  289. total = statusex.ullTotalPhys / GBYTES;
  290. avl = statusex.ullAvailPhys / GBYTES;
  291. remain_avl = statusex.ullAvailPhys % GBYTES;
  292. if (remain_total > 0)
  293. decimal_total = (remain_total / MBYTES) / DKBYTES;
  294. if (remain_avl > 0)
  295. decimal_avl = (remain_avl / MBYTES) / DKBYTES;
  296. decimal_total += (double)total;
  297. decimal_avl += (double)avl;
  298. char buffer[kMaxInfoBuffer];
  299. sprintf_s(buffer, kMaxInfoBuffer, "total %.2f GB (%.2f GB available)", decimal_total, decimal_avl);
  300. memory_info.append(buffer);
  301. }
  302. std::cout << "Memory size:" << memory_info << std::endl;
  303. }
  304. // ---- get harddisk info ---- //
  305. std::string execCmd(const char *cmd)
  306. {
  307. char buffer[128] = { 0 };
  308. std::string result;
  309. FILE *pipe = _popen(cmd, "r");
  310. if (!pipe) throw std::runtime_error("_popen() failed!");
  311. while (!feof(pipe))
  312. {
  313. if (fgets(buffer, 128, pipe) != NULL)
  314. result += buffer;
  315. }
  316. _pclose(pipe);
  317. return result;
  318. }
  319. void getHardDiskInfo()
  320. {
  321. std::string hd_seiral = execCmd("wmic path win32_physicalmedia get SerialNumber");
  322. std::cout << "HardDisk Serial Number: " << hd_seiral << std::endl;
  323. }
  324. // ---- get network info ---- //
  325. void getNetworkInfo()
  326. {
  327. // PIP_ADAPTER_INFO struct contains network information
  328. PIP_ADAPTER_INFO pIpAdapterInfo = new IP_ADAPTER_INFO();
  329. unsigned long adapter_size = sizeof(IP_ADAPTER_INFO);
  330. int ret = GetAdaptersInfo(pIpAdapterInfo, &adapter_size);
  331. if (ret == ERROR_BUFFER_OVERFLOW)
  332. {
  333. // overflow, use the output size to recreate the handler
  334. delete pIpAdapterInfo;
  335. pIpAdapterInfo = (PIP_ADAPTER_INFO)new BYTE[adapter_size];
  336. ret = GetAdaptersInfo(pIpAdapterInfo, &adapter_size);
  337. }
  338. if (ret == ERROR_SUCCESS)
  339. {
  340. int card_index = 0;
  341. // may have many cards, it saved in linklist
  342. while (pIpAdapterInfo)
  343. {
  344. std::cout << "---- " << "NetworkCard " << ++card_index << " ----" << std::endl;
  345. std::cout << "Network Card Name: " << pIpAdapterInfo->AdapterName << std::endl;
  346. std::cout << "Network Card Description: " << pIpAdapterInfo->Description << std::endl;
  347. // get IP, one card may have many IPs
  348. PIP_ADDR_STRING pIpAddr = &(pIpAdapterInfo->IpAddressList);
  349. while (pIpAddr)
  350. {
  351. char local_ip[128] = { 0 };
  352. strcpy(local_ip, pIpAddr->IpAddress.String);
  353. std::cout << "Local IP: " << local_ip << std::endl;
  354. pIpAddr = pIpAddr->Next;
  355. }
  356. char local_mac[128] = { 0 };
  357. int char_index = 0;
  358. for (int i = 0; i < pIpAdapterInfo->AddressLength; i++)
  359. {
  360. char temp_str[10] = { 0 };
  361. sprintf(temp_str, "%02X-", pIpAdapterInfo->Address[i]); // X for uppercase, x for lowercase
  362. strcpy(local_mac + char_index, temp_str);
  363. char_index += 3;
  364. }
  365. local_mac[17] = '\0'; // remove tail '-'
  366. std::cout << "Local Mac: " << local_mac << std::endl;
  367. // here just need the first card info
  368. break;
  369. // iterate next
  370. //pIpAdapterInfo = pIpAdapterInfo->Next;
  371. }
  372. }
  373. if (pIpAdapterInfo)
  374. delete pIpAdapterInfo;
  375. }
  376. // ---- get process info ---- //
  377. void getProcessInfo()
  378. {
  379. int pid = GetCurrentProcessId();
  380. // TODO: cpu and mem usage
  381. printf("Current Pid: %d\n", pid);
  382. }
  383. std::string WStringToString(const std::wstring &wstr)
  384. {
  385. std::string str(wstr.length(), ' ');
  386. std::copy(wstr.begin(), wstr.end(), str.begin());
  387. return str;
  388. }
  389. /*GPU*/
  390. void getGPU() {
  391. // 参数定义
  392. IDXGIFactory * pFactory;
  393. IDXGIAdapter * pAdapter;
  394. std::vector <IDXGIAdapter*> vAdapters; // 显卡
  395. // 显卡的数量
  396. int iAdapterNum = 0;
  397. // 创建一个DXGI工厂
  398. HRESULT hr = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)(&pFactory));
  399. if (FAILED(hr))
  400. return;
  401. // 枚举适配器
  402. while (pFactory->EnumAdapters(iAdapterNum, &pAdapter) != DXGI_ERROR_NOT_FOUND)
  403. {
  404. vAdapters.push_back(pAdapter);
  405. ++iAdapterNum;
  406. }
  407. // 信息输出
  408. //std::cout << "===============获取到" << iAdapterNum << "块显卡===============" << std::endl;
  409. for (size_t i = 0; i < vAdapters.size(); i++)
  410. {
  411. //std::cout << "Video card" << i + 1 << ":" << std::endl;
  412. // 获取信息
  413. DXGI_ADAPTER_DESC adapterDesc;
  414. vAdapters[i]->GetDesc(&adapterDesc);
  415. std::wstring aa(adapterDesc.Description);
  416. std::string bb = WStringToString(aa);
  417. std::cout << "Video card " << i + 1 << " DedicatedVideoMemory:" << adapterDesc.DedicatedVideoMemory / 1024 / 1024 << "M" << std::endl;
  418. std::cout << "Video card " << i + 1 << " SharedSystemMemory:" << adapterDesc.SharedSystemMemory / 1024 / 1024 << "M" << std::endl;
  419. // 输出显卡信息
  420. //std::cout << "系统视频内存:" << adapterDesc.DedicatedSystemMemory / 1024 / 1024 << "M" << std::endl;
  421. //std::cout << "专用视频内存:" << adapterDesc.DedicatedVideoMemory / 1024 / 1024 << "M" << std::endl;
  422. //std::cout << "共享系统内存:" << adapterDesc.SharedSystemMemory / 1024 / 1024 << "M" << std::endl;
  423. //std::cout << "设备描述:" << bb.c_str() << std::endl;
  424. //std::cout << "设备ID:" << adapterDesc.DeviceId << std::endl;
  425. //std::cout << "PCI ID修正版本:" << adapterDesc.Revision << std::endl;
  426. //std::cout << "子系统PIC ID:" << adapterDesc.SubSysId << std::endl;
  427. //std::cout << "厂商编号:" << adapterDesc.VendorId << std::endl;
  428. // 输出设备
  429. IDXGIOutput * pOutput;
  430. std::vector<IDXGIOutput*> vOutputs;
  431. // 输出设备数量
  432. int iOutputNum = 0;
  433. while (vAdapters[i]->EnumOutputs(iOutputNum, &pOutput) != DXGI_ERROR_NOT_FOUND)
  434. {
  435. vOutputs.push_back(pOutput);
  436. iOutputNum++;
  437. }
  438. //std::cout << std::endl;
  439. //std::cout << "该显卡获取到" << iOutputNum << "个显示设备:" << std::endl;
  440. for (size_t n = 0; n < vOutputs.size(); n++)
  441. {
  442. // 获取显示设备信息
  443. DXGI_OUTPUT_DESC outputDesc;
  444. vOutputs[n]->GetDesc(&outputDesc);
  445. // 获取设备支持
  446. UINT uModeNum = 0;
  447. DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM;
  448. UINT flags = DXGI_ENUM_MODES_INTERLACED;
  449. vOutputs[n]->GetDisplayModeList(format, flags, &uModeNum, 0);
  450. DXGI_MODE_DESC * pModeDescs = new DXGI_MODE_DESC[uModeNum];
  451. vOutputs[n]->GetDisplayModeList(format, flags, &uModeNum, pModeDescs);
  452. //std::cout << "DisplayDevice:" << n + 1 << " Name:" << outputDesc.DeviceName << std::endl;
  453. std::cout << "DisplayDevice " << n + 1 << " Resolution ratio:" << outputDesc.DesktopCoordinates.right - outputDesc.DesktopCoordinates.left << "*" << outputDesc.DesktopCoordinates.bottom - outputDesc.DesktopCoordinates.top << std::endl;
  454. // 所支持的分辨率信息
  455. //std::cout << "分辨率信息:" << std::endl;
  456. /*for (UINT m = 0; m < uModeNum; m++)
  457. {
  458. std::cout << "== 分辨率:" << pModeDescs[m].Width << "*" << pModeDescs[m].Height << " 刷新率" << (pModeDescs[m].RefreshRate.Numerator) / (pModeDescs[m].RefreshRate.Denominator) << std::endl;
  459. }*/
  460. }
  461. vOutputs.clear();
  462. }
  463. vAdapters.clear();
  464. }
  465. int main(int argc, char *argv[])
  466. {
  467. //std::cout << "操作系统版本:" << std::endl;
  468. getOsInfo();
  469. //std::cout << "CPU:" << std::endl;
  470. getCpuInfo();
  471. //std::cout << "内存大小:" << std::endl;
  472. getMemoryInfo();
  473. //std::cout << "GPU:" << std::endl;
  474. getGPU();
  475. std::cout << "=== harddisk information ===" << std::endl;
  476. getHardDiskInfo();
  477. std::cout << "=== network information ===" << std::endl;
  478. getNetworkInfo();
  479. printf("=== process information ===\n");
  480. getProcessInfo();
  481. //std::cout << "显卡驱动:" << std::endl;
  482. getDriver();
  483. return 0;
  484. }

 

electron获取电脑硬件信息,主线程调用c++程序,读取其输出的数据。

参考 electron 启动exe 程序

  1. function runExec() {
  2. // 执行命令行,如果命令不需要路径,或就是项目根目录,则不需要cwd参数:
  3. let workerProcess = exec('sys.exe', {})
  4. // 不受child_process默认的缓冲区大小的使用方法,没参数也要写上{}:workerProcess = exec(cmdStr, {})
  5. // 打印正常的后台可执行程序输出
  6. workerProcess.stdout.on('data', function(data) {
  7. console.log('stdout: ' + data)
  8. })
  9. // 打印错误的后台可执行程序输出
  10. workerProcess.stderr.on('data', function(data) {
  11. console.log('stderr: ' + data)
  12. })
  13. // 退出之后的输出
  14. workerProcess.on('close', function(code) {
  15. console.log('out code:' + code)
  16. })
  17. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/245708
推荐阅读
相关标签
  

闽ICP备14008679号