9月20日学习记录

编程入门 行业动态 更新时间:2024-10-12 03:22:35

9月20日学习记录

9月20日学习记录

通过下面的代码可以实现使用c++快速获得uuid:

使用chatgpt生成的:

#include <WinSock2.h>
#include <windows.h>
#include <Wbemidl.h>
#include <iostream>
#include <DXGI.h>
#include <comdef.h>
#include <iostream>
#include <QDebug>
using namespace std;
#pragma comment(lib,"DXGI.lib")
#pragma warning(disable: 4996)
#pragma comment(lib, "wbemuuid.lib")QString getMachineUUID()
{QString uuid = "";HRESULT hres = CoInitializeEx(0, COINIT_APARTMENTTHREADED);if ((hres != RPC_E_TOO_LATE) && (hres != RPC_E_NO_GOOD_SECURITY_PACKAGES) && FAILED(hres)){qDebug() << "Failed to initialize security. "<< "Error code = 0x"<< hex << hres << endl;CoUninitialize();return uuid;}hres = CoInitializeSecurity(NULL,-1,                          // COM authenticationNULL,                        // Authentication servicesNULL,                        // ReservedRPC_C_AUTHN_LEVEL_DEFAULT,   // Default authenticationRPC_C_IMP_LEVEL_IMPERSONATE, // Default ImpersonationNULL,                        // Authentication infoEOAC_NONE,                   // Additional capabilitiesNULL                         // Reserved);if ((hres != RPC_E_TOO_LATE) && FAILED(hres)){qDebug() << "Failed to initialize security. Error code = 0x"<< hex << hres << endl;CoUninitialize();return uuid;                    // 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)){qDebug() << "Failed to create IWbemLocator object."<< " Err code = 0x"<< hex << hres << endl;CoUninitialize();return uuid;                 // Program has failed.}// Step 4: -----------------------------------------------------// Connect to WMI through the IWbemLocator::ConnectServer methodIWbemServices* 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 namespaceNULL,                    // User name. NULL = current userNULL,                    // User password. NULL = current0,                       // Locale. NULL indicates currentNULL,                    // Security flags.0,                       // Authority (e.g. Kerberos)0,                       // Context object&pSvc                    // pointer to IWbemServices proxy);if (FAILED(hres)){qDebug() << "Could not connect. Error code = 0x"<< hex << hres << endl;pLoc->Release();CoUninitialize();return uuid;                // 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 setRPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxxRPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxxNULL,                        // Server principal nameRPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxxRPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxxNULL,                        // client identityEOAC_NONE                    // proxy capabilities);if (FAILED(hres)){cout << "Could not set proxy blanket. Error code = 0x"<< hex << hres << endl;pSvc->Release();pLoc->Release();CoUninitialize();return uuid;               // Program has failed.}// Step 6: --------------------------------------------------// Use the IWbemServices pointer to make requests of WMI ----// For example, get the name of the operating systemIEnumWbemClassObject* pEnumerator = NULL;hres = pSvc->ExecQuery(bstr_t("WQL"),bstr_t("SELECT UUID FROM Win32_ComputerSystemProduct"),WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumerator);if (FAILED(hres)){qDebug() << "Query for operating system name failed."<< " Error code = 0x"<< hex << hres << endl;pSvc->Release();pLoc->Release();CoUninitialize();return uuid;               // 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 (FAILED(hr) || 0 == uReturn){break;}VARIANT vtProp;// Get the value of the Name property/*hr = pclsObj->Get(L"VolumeName", 0, &vtProp, 0, 0);wcout << " VolumeName : " << vtProp.bstrVal << endl;VariantClear(&vtProp);*/if (FAILED(pclsObj->Get(L"UUID", 0, &vtProp, 0, 0))){qDebug() << "The specified property is not found." << endl;}else{qDebug() << vtProp.bstrVal << endl;QString q_str((QChar*)vtProp.bstrVal, wcslen(vtProp.bstrVal));uuid = q_str;}pclsObj->Release();}// Cleanup// ========pSvc->Release();pLoc->Release();pEnumerator->Release();// pclsObj->Release();CoUninitialize();qDebug() << "uuid: " << uuid << endl;return uuid;
}

速度在75ms

通过下面博客的代码可以实现获得CPUID:

【C/C++】获取计算机CPUID序列号_c++ 获取cpu序列号-CSDN博客

std::string GetId()
{std::string strCPUId;unsigned long s1, s2;char buf[32] = { 0 };__asm{mov eax, 01hxor edx, edxcpuidmov s1, edxmov s2, eax}if (s1){memset(buf, 0, 32);sprintf_s(buf, 32, "%08X", s1);strCPUId += buf;}if (s2){memset(buf, 0, 32);sprintf_s(buf, 32, "%08X", s2);strCPUId += buf;}__asm{mov eax, 03hxor ecx, ecxxor edx, edxcpuidmov s1, edxmov s2, ecx}if (s1){memset(buf, 0, 32);sprintf_s(buf, 32, "%08X", s1);strCPUId += buf;}if (s2){memset(buf, 0, 32);sprintf_s(buf, 32, "%08X", s2);strCPUId += buf;}return strCPUId;
}

使用该函数将string转为QString

QString::fromStdString(GetCPUId()); 

时间消耗: 

#include <iostream>
#include <windows.h>int main() {HKEY hKey;if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Cryptography", 0, KEY_READ, &hKey) == ERROR_SUCCESS) {BYTE data[100];DWORD dataSize = sizeof(data);if (RegQueryValueEx(hKey, "MachineGuid", NULL, NULL, data, &dataSize) == ERROR_SUCCESS) {std::string machineGUID(reinterpret_cast<char*>(data));std::cout << "MachineGUID: " << machineGUID << std::endl;}RegCloseKey(hKey);}return 0;
}

Time elapsed: 24600 ns
Time elapsed: 0 ms

 chatgpt真的很好用

获取MachineGUID

Windows API 获取MachineGUID_浇糖玛奇朵的博客-CSDN博客

(1)64位程序,64位电脑 

#include <Windows.h>
#include <string>
#include <iostream>
int main()
{std::string sub_key = "SOFTWARE\\Microsoft\\Cryptography";std::string name = "MachineGuid";HKEY hKey;DWORD dwType = REG_SZ;DWORD dwLen = MAX_PATH;if (RegOpenKeyA(HKEY_LOCAL_MACHINE, sub_key.c_str(), &hKey) == ERROR_SUCCESS) {std::cout << "ok\n";}unsigned char buf[100];PLONG data = 0;if (RegQueryValueExA(hKey, name.c_str(), 0, &dwType, (LPBYTE)buf, &dwLen) == ERROR_SUCCESS) {std::cout << "ok\n";}else std::cout << "GetLastError() = " << GetLastError() << std::endl;std::cout << buf << std::endl;return 0;
}

注意:

我的电脑是64位的,所以我的程序也得是64位才行,才能正确获得结果,否则,就访问失败。

这是一个非常重要的点,,,让我在坑里爬不出来。

【小沐学C++】C++ 访问注册表(64位系统)_c++ 32位及64位 注册表读写_爱看书的小沐的博客-CSDN博客

64位系统注册表分32位注册表项和64位注册表项两部分。

64位系统中,通过regedit中查看指定路径下的注册表项均为64位注册表项。

而32位注册表项被重定位到:HKEY_LOCAL_MACHINE\Software\WOW6432Node

(2) 写成下面这样就可以在32位应用程序中访问64位的注册表了。

#include <Windows.h>
#include <string>
#include <iostream>
int main()
{std::string name = "MachineGuid";HKEY hKey;DWORD dwType = REG_SZ;DWORD dwLen = MAX_PATH;if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Cryptography",0, KEY_READ | KEY_WOW64_64KEY, &hKey) == ERROR_SUCCESS){std::cout << "ok\n";}unsigned char buf[100];PLONG data = 0;if (RegQueryValueExA(hKey, name.c_str(), 0, &dwType, (LPBYTE)buf, &dwLen) == ERROR_SUCCESS) {std::cout << "ok\n";}else std::cout << "GetLastError() = " << GetLastError() << std::endl;std::cout << buf << std::endl;return 0;
}

关键:KEY_WOW64_64KEY,它可以使32位程序访问64位系统的64位注册表。

(3)封装一下:

QString getMachineGUID()
{std::string name = "MachineGuid";HKEY hKey;DWORD dwType = REG_SZ;DWORD dwLen = MAX_PATH;if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Cryptography",0, KEY_READ | KEY_WOW64_64KEY, &hKey) == ERROR_SUCCESS){std::cout << "ok\n";}unsigned char buf[100];PLONG data = 0;if (RegQueryValueExA(hKey, name.c_str(), 0, &dwType, (LPBYTE)buf, &dwLen) == ERROR_SUCCESS) {std::cout << "ok\n";}else std::cout << "GetLastError() = " << GetLastError() << std::endl;QString qstr = "";char* p = (char*)buf;qstr = qstr.append(p);qDebug() << qstr;return qstr;
}

花费时间: 

Time elapsed: 149100 ns
Time elapsed: 0 ms

(4)Qt中获取MachineGuid

 计算机\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography

如果是Qt5.7以上的版本,

系统是64位,程序是32位,

可以使用下面文章的方法。

QSettings读取注册表失败_qsettings::registry64format_蓝黑墨水的博客-CSDN博客

    QSettings settings("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography",QSettings::Registry64Format);QString value = settings.value("MachineGuid", "").toString();//读qDebug()<<value;

 主板ID(又名BIOS-ID):

  (又名主板序列号)

BIOS:basic input output system:

它本身是代码段,作为开机之后,CPU要进行处理的第一个“可执行程序”,也就是第一个“开机启动项。

cmd.exe中查询:

wmic baseboard get serialnumber

方法1:

VC++ 通过wmic获取主板和BIOS序列号_c++ wmic_老狼主的博客-CSDN博客

std::string GetHardwareSerialNumber()
{std::string sResult;const long COMMAND_SIZE = 1020;const DWORD WAIT_TIME = 1000; // INFINITE// 获取主板序列号char str1[] = "wmic BaseBoard get SerialNumber";TCHAR szFetCmd[100];MultiByteToWideChar(CP_ACP, 0, str1, -1, szFetCmd, 100);const std::string strEnSearch = "SerialNumber";    // 前导信息// 获取BIOS序列号//TCHAR szFetCmd[] = _T("wmic bios get serialnumber");// 命令行//const std::string strEnSearch = "SerialNumber";    // 前导信息// 获取CPU序号名//TCHAR szFetCmd[] = "wmic cpu get processorid";  // 命令行//const string strEnSearch = "ProcessorId";       // 前导信息BOOL bReturnCode = FALSE;HANDLE hReadPipe = NULL;  // Pipeline for READHANDLE hWritePipe = NULL; // Pipeline for WRITEPROCESS_INFORMATION pi;   // Process informationSTARTUPINFO         si;   // Control-command window infoSECURITY_ATTRIBUTES sa;   // Security attributeschar szBuffer[COMMAND_SIZE + 1] = { 0 }; // Command line output bufferstd::string strBuffer;DWORD count = 0;size_t pos = 0;size_t i = 0;size_t j = 0;char* lpszBaseBoard = (char*)malloc((COMMAND_SIZE + 1) * sizeof(char));memset(lpszBaseBoard, 0x00, (COMMAND_SIZE + 1) * sizeof(char));memset(&pi, 0, sizeof(pi));memset(&si, 0, sizeof(si));memset(&sa, 0, sizeof(sa));pi.hProcess = NULL;pi.hThread = NULL;si.cb = sizeof(STARTUPINFO);sa.nLength = sizeof(SECURITY_ATTRIBUTES);sa.lpSecurityDescriptor = NULL;sa.bInheritHandle = TRUE;bReturnCode = CreatePipe(&hReadPipe, &hWritePipe, &sa, 0);if (!bReturnCode)goto EXIT;GetStartupInfo(&si);si.hStdError = hWritePipe;si.hStdOutput = hWritePipe;si.wShowWindow = SW_HIDE; // hide command line windowsi.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;bReturnCode = CreateProcess(NULL, szFetCmd, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);if (!bReturnCode)goto EXIT;WaitForSingleObject(pi.hProcess, WAIT_TIME);bReturnCode = ReadFile(hReadPipe, szBuffer, COMMAND_SIZE, &count, 0);if (!bReturnCode)goto EXIT;bReturnCode = FALSE;strBuffer = szBuffer;pos = strBuffer.find(strEnSearch);if (pos < 0) // NOT FOUNDgoto EXIT;elsestrBuffer = strBuffer.substr(pos + strEnSearch.length());memset(szBuffer, 0x00, sizeof(szBuffer));strcpy_s(szBuffer, strBuffer.c_str());j = 0;for (i = 0; i < strlen(szBuffer); i++){if (szBuffer[i] != ' ' && szBuffer[i] != '\n' && szBuffer[i] != '\r'){lpszBaseBoard[j] = szBuffer[i];j++;}}sResult = lpszBaseBoard;bReturnCode = TRUE;EXIT:free(lpszBaseBoard);CloseHandle(hWritePipe);CloseHandle(hReadPipe);CloseHandle(pi.hProcess);CloseHandle(pi.hThread);return sResult;
}

 耗时:

Time elapsed: 1431615600 ns
Time elapsed: 1431 ms

方法2:

chatgpt生成

int GetSerialNumber()
{FILE* cmd = _popen("wmic baseboard get serialnumber", "r");if (cmd == NULL) {printf("Failed to execute command.\n");return 1;}char buffer[256];while (fgets(buffer, sizeof(buffer), cmd) != NULL) {printf("%s", buffer);}_pclose(cmd);
}
Time elapsed: 2949781600 ns
Time elapsed: 2949 ms

 获取软件信息

Qt 获取当前计算机已安装的软件(注册表方式)_qt5获取电脑软件信息_不随。的博客-CSDN博客

计算机\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

void getSoftware()
{QString regStr = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\";QSettings settings(regStr, QSettings::NativeFormat);QStringList regGroups = settings.childGroups();foreach(QString regItem, regGroups){settings.beginGroup(regItem);QString displayName = settings.value("DisplayName").toString();QString uninstallString = settings.value("UninstallString").toString();if (!displayName.isEmpty()){qDebug() << "[" << __FUNCTION__ << __LINE__ << "] :" << displayName << uninstallString;}settings.endGroup();}
}
[ getSoftware 47 ] : "Visual Studio Community 2017" "\"C:\\Program Files (x86)\\Microsoft Visual Studio\\Installer\\setup.exe\" uninstall --installPath \"E:\\VS2017\\VisualStudio\""
[ getSoftware 47 ] : "Adobe Flash Player 34 ActiveX" "C:\\WINDOWS\\SysWOW64\\Macromed\\Flash\\FlashUtil32_34_0_0_289_ActiveX.exe -maintain activex"

(3 封私信 / 25 条消息) 电脑中的注册表是什么? - 知乎 (zhihu)

注册表由键,子键,值项构成。

一个键就是分支中的一个文件夹

而子键就是这个文件夹当中的子文件夹

子键同样是一个键。

一个值项则是一个键的当前定义

名称,数据类型,分配的值组成。

一个键可以有一个或多个值

更多推荐

9月20日学习记录

本文发布于:2024-02-17 09:23:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1693509.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!